require可以执行其他文件的内容。
新建文件: nodes.js:
1 | console.log('start nodes.js'); |
app.js:
1234567891011121314151617 | //打印字符串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 |
输出字符串
123 | Start app.start nodes.jsThe "data to append" was appended to file! |
nodes.js:
123 | console.log('start nodes.js');module.exports.age = 25; |
app.js:
1234567891011121314151617 | //打印字符串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:
123456 | console.log('start nodes.js');module.exports.addNote = ()=>{ console.log('addNode'); return 'New Node';}; |
app.js:
123456 | console.log('Start app.');const nodes = require('./nodes.js') const res = nodes.addNote();console.log(res); |
打开控制台,在当前目录下输入:
1 | > node app.js |
输出字符串
1234 | Start app.start nodes.jsaddNodeNew Node |
nodes.js:
1234567891011 | console.log('start nodes.js');module.exports.add = (a,b)=>{ return a+b;};module.exports.addNote = ()=>{ console.log('addNode'); return 'New Node';}; |
app.js:
1234567 | //打印字符串console.log('Start app.');const nodes = require('./nodes.js') const res = nodes.add(1,2);console.log(res); |
打开控制台,在当前目录下输入:
1 | > node app.js |
输出字符串
123 | Start app.start nodes.js3 |
本文链接: https://dreamerjonson.com/2018/11/13/node-3-require/
版权声明: 本博客所有文章除特别声明外,均采用 CC BY 4.0 CN协议 许可协议。转载请注明出处!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。