Reputation: 112
I would like to use a function (called connector) from another JS file (B.js) in a main file (A.js), because the function connector in B.js needs the values calculated in A.js, and other functions in B.js are triggered by connector.
I saw that it was possible to launch entire scripts using Node JS Command Line, but I was not able to find a similar operation for specific functions in a script.
I tried to use var exports.connector = function connector(args) {
in B.js and then require
in A.js, but is looks impossible as B.js does not belong to the same folder or even branch of the project structure, so I keep getting the error message "Cannot find module './scripts/B.js'" (A.js is in ./server/A.js).
I looked at process.argv
from Node JS, this can help me save the values from A.js and maybe get them in B.js, but this will not help triggering the connector function in A.js.
So is there a way to use connector in A.js without having to paste all B.js code in it?
Upvotes: 0
Views: 795
Reputation: 70830
Use ..
for getting up a directory, and so if you have, for example, base directory with directory 'server' that has 'A.js' and directory 'scripts' that has 'B.js', use the following statement to import B.js from A.js:
const b = require('./../scripts/B.js');
Or, you can use ES6 syntax, like this:
// scripts/B.js
export function func1(...) {
...
}
export function func2(...) {
...
}
// server/A.js
import * as b from './../scripts/B.js';
b.func1(...);
b.func2(...);
Upvotes: 2