nodejs如何调用其他的js文件内容?使用指南
将其他js文件与nodejs文件放在同一目录下,然后在nodejs文件中使用require(‘js文件路径’);将其他js文件引入到nodejs文件中,就可以直接调用其他js文件内容了。
nodejs调用其他的js文件内容的方法如下:
基本语句
require(‘js文件路径’);
使用方法
给大家举个简单的栗子(假设fun1,fun2,fun3文件在同一个目录下)
fun1.js
var fun2 = require('./fun2');
var fun3 = require('./fun3');
function fun1(){
console.log("我是fun1");
fun2.add(1,2);
fun3();
}
fun1();
fun2.js
module.exports = {
reduce:function(a,b){
console.log("我是fun2的reduce方法");
console.log(a-b);
},
add:function(a,b){
console.log("我是fun2的add方法");
console.log(a+b);
}
}
还有一种更合适的写法是:
function reduce(a,b){
console.log("我是fun2的reduce方法");
console.log(a-b);
},
function add(a,b){
console.log("我是fun2的add方法");
console.log(a+b);
}
module.exports = {
reduce,
add
}
这种写法就可以只把别的文件需要调用的函数导出,未导出的函数别的js文件是用不了的。
fun3.js
module.exports = function print(){
console.log("我是fun3的方法");
}
输出
输出结果为:
我是fun1
我是fun2的add方法:
3
我是fun3的方法