nodejs渐入佳境[3]-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
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
本文链接:https://dreamerjonson.com/2018/11/13/node-3-require/
版权声明:本博客所有文章除特别声明外,均采用CC BY 4.0 CN协议许可协议。转载请注明出处!
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。