Home > Web Front-end > JS Tutorial > body text

How node.js references external js

(*-*)浩
Release: 2019-05-24 14:28:48
Original
3842 people have browsed it

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.

How node.js references external js

##Basic statements

require('js文件路径');
Copy after login

How to use

For example, in the same directory, there are three js files fun, fun1, and fun2.

fun.js

var fun1 = require('./fun1');
var fun2 = require('./fun2');

function test(){
     console.log("调用了fun的test方法");
     fun1.add(1,2);
     fun2();
}
     test();
Copy after login
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
}
Copy after login
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();
Copy after login
You can see that the writing methods of fun1 and fun2 are slightly different. Fun1 This way of writing is better, because it can only export functions that need to be called by other files. Unexported functions cannot be used by other js files.

The output results are as follows:

调用了app的test方法
调用了fun1的add方法
3
调用了fun2的print方法
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!