今天在写程序的时候需要引用另一个js文件中的函数,迅速懵逼,幸好有大佬指路让我搜一下nodejs怎么引用文件,最后终于研究出来了。

基本语句
require('js文件路径');使用方法
举个例子,在同一个目录下,有fun、fun1、fun2三个js文件。
fun.js
var fun1 = require('./fun1');
var fun2 = require('./fun2');
function test(){
console.log("调用了fun的test方法");
fun1.add(1,2);
fun2();
}
test();fun1.js
function reduce(a,b){
console.log("调用了fun1的reduce方法");
console.log(a-b);
}
function add(a,b){
console.log("调用了fun1的add方法");
console.log(a+b);
}
module.exports = {
reduce,
add
}fun2.js
module.exports = function print(){
console.log("调用了fun2的print方法");
}
这种的调用方法为: fun2();
或者
module.exports = {
print:function(){
console.log("调用了fun2的print方法");
},
copy:function(a,b){
console.log("我是fun2的copy方法");
}
}
这种的调用方法为:fun2.print();可以看到fun1和fun2的写法略有不同,fun1这种写法更好,因为它可以只把别的文件需要调用的函数导出,未导出的函数别的js文件是用不了的
输出结果如下:
调用了app的test方法 调用了fun1的add方法 3 调用了fun2的print方法
以上就是node.js怎么引用外部js的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号