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

发布时间:2020-08-05 15:21:17 作者:jonson_jackson
来源:网络 阅读:547

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

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

推荐阅读:
  1. 社交+教育APP系统:促进教育行业智慧升级
  2. 区块链内容分享挖矿系统:新型社交化数字营销平台

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

区块链 前端 nodejs

上一篇:kotlin中的高级特性--协变与逆变(反变)

下一篇:C++实现顺序表

相关阅读

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

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