node[3]-require

require 导入其他文件

require可以执行其他文件的内容。

新建文件: nodes.js:

1
console.log('start nodes.js');

app.js:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
//打印字符串
console.log('Start app.');

const nodes = require('./nodes.js')
//导入node自带modules,fs文件操作
const fs = require('fs');
//os系统操作
const os = require('os');
//获取系统名字
var user = os.userInfo();

//添加字符串到回调函数中,并执行回调函数。出错就会报错,不出错就会打印出'The "data to append" was appended to file!'
fs.appendFile('greetings.txt',`Hello ${user.username}`,(err) => {
  if (err) throw err;
  console.log('The "data to append" was appended to file!');
}
);

打开控制台,在当前目录下输入:

1
> node app.js

输出字符串

1
2
3
Start app.
start nodes.js
The "data to append" was appended to file!

require 导入属性

nodes.js:

1
2
3
console.log('start nodes.js');

module.exports.age = 25;

app.js:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
//打印字符串
console.log('Start app.');

const nodes = require('./nodes.js')
//导入node自带modules,fs文件操作
const fs = require('fs');
//os系统操作
const os = require('os');
//获取系统名字
var user = os.userInfo();

//添加字符串到回调函数中,并执行回调函数。出错就会报错,不出错就会打印出'The "data to append" was appended to file!'
fs.appendFile('greetings.txt',`Hello ${user.username} age ${nodes.age}`,(err) => {
  if (err) throw err;
  console.log('The "data to append" was appended to file!');
}
);

打开控制台,在当前目录下输入:

1
> node app.js

文件中存储:Hello jackson age 25

require 导入函数

nodes.js:

1
2
3
4
5
6
console.log('start nodes.js');

module.exports.addNote = ()=>{
  console.log('addNode');
  return 'New Node';
};

app.js:

1
2
3
4
5
6
console.log('Start app.');

const nodes = require('./nodes.js')

 const res = nodes.addNote();
console.log(res);

打开控制台,在当前目录下输入:

1
> node app.js

输出字符串

1
2
3
4
Start app.
start nodes.js
addNode
New Node

require 导入带参函数

nodes.js:

1
2
3
4
5
6
7
8
9
10
11
console.log('start nodes.js');

module.exports.add = (a,b)=>{

  return a+b;
};

module.exports.addNote = ()=>{
  console.log('addNode');
  return 'New Node';
};

app.js:

1
2
3
4
5
6
7
//打印字符串
console.log('Start app.');

const nodes = require('./nodes.js')

 const res = nodes.add(1,2);
console.log(res);

打开控制台,在当前目录下输入:

1
> node app.js

输出字符串

1
2
3
Start app.
start nodes.js
3

 

郑建勋(jonson)区块链工程师 & Web工程师

灾难总是接踵而至,这正是世间的常理。你以为只要哭诉一下,就会有谁来救你吗?如果失败了,就只能说明我不过是如此程度的男人。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值