温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

nodejs渐入佳境[3]-require导入模块

发布时间:2020-08-05 15:21:17 来源:网络 阅读:549 作者:jonson_jackson 栏目:开发技术

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
  • 本文链接: https://dreamerjonson.com/2018/11/13/node-3-require/

  • 版权声明: 本博客所有文章除特别声明外,均采用 CC BY 4.0 CN协议 许可协议。转载请注明出处!

nodejs渐入佳境[3]-require导入模块

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI