Today when I was writing a program, I needed to reference a function in another js file, and I was quickly confused. Fortunately, a big boss gave me some guidance and asked me to search how to reference files in nodejs, and I finally figured it out.
##Basic statements
require('js文件路径');
How to use
For example, in the same directory, there are three js files fun, fun1, and fun2. fun.jsvar fun1 = require('./fun1'); var fun2 = require('./fun2'); function test(){ console.log("调用了fun的test方法"); fun1.add(1,2); fun2(); } test();
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 }
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();
The output results are as follows:
调用了app的test方法 调用了fun1的add方法 3 调用了fun2的print方法
The above is the detailed content of How node.js references external js. For more information, please follow other related articles on the PHP Chinese website!