简体   繁体   中英

Include JS files using function from other JS file in Node

I have been trying this stuff a lot but I am unable to get around with this stuff. I have 2 JS files, add.js and console.js.

add.js

module.exports = {
    add: function add(a,b){
        return a+b;
    }
};

console.js

module.exports = {
    debug: function debug(a,b){
        console.log(add(a,b));
    }
};

A part of app.js code

app.js

var add = require('./add').add;
var debug = require('./console');
console.log(debug.debug(3,4));

This is throwing me an error in console. "add is not defined" referencing the add of console.log(add(a,b)) in console.js

So, in general is there a way where we can write all the requires in one place (in order) and the things work automatically. For example, we do the same in javascript.

<script src="add.js"/>
<script src="console.js"/>

And the thing works. But how to do the same stuff in Node JS.

If you want to use add function in console.js file, you should require add.js file in console js file. Error says about add function which you have used in console.js file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM