使用Node JS命令行从另一个文件执行函数

时间:2022-04-01 16:00:29

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.

我想在主文件(A.js)中使用来自另一个JS文件(B.js)的函数(称为连接器),因为B.js中的函数连接器需要在A.js中计算的值,以及其他函数在B.js中由连接器触发。

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.

我看到可以使用Node JS命令行启动整个脚本,但是我无法在脚本中找到针对特定功能的类似操作。

I tried to use var exports.connector = function connector(args) { in B.js and then requirein 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).

我尝试使用var exports.connector = function connector(args){在B.js然后要求A.js,但看起来不可能,因为B.js不属于同一个文件夹甚至属于项目结构的分支,所以我不断收到错误消息“找不到模块'./scripts/B.js'”(A.js在./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.

我查看了来自Node JS的process.argv,这可以帮助我保存A.js中的值并可能在B.js中获取它们,但这无助于触发A.js中的连接器功能。

So is there a way to use connector in A.js without having to paste all B.js code in it?

那么有没有办法在A.js中使用连接器而不必粘贴所有B.js代码?

1 个解决方案

#1


2  

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:

使用..来获取一个目录,所以如果你有一个基本目录,目录'server'有'A.js',目录'scripts'有'B.js',请使用以下语句从A.js导入B.js:

const b = require('./../scripts/B.js');

Or, you can use ES6 syntax, like this:

或者,您可以使用ES6语法,如下所示:

// scripts/B.js
export function func1(...) {
  ...
}

export function func2(...) {
  ...
}

// server/A.js
import * as b from './../scripts/B.js';

b.func1(...);
b.func2(...);

#1


2  

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:

使用..来获取一个目录,所以如果你有一个基本目录,目录'server'有'A.js',目录'scripts'有'B.js',请使用以下语句从A.js导入B.js:

const b = require('./../scripts/B.js');

Or, you can use ES6 syntax, like this:

或者,您可以使用ES6语法,如下所示:

// scripts/B.js
export function func1(...) {
  ...
}

export function func2(...) {
  ...
}

// server/A.js
import * as b from './../scripts/B.js';

b.func1(...);
b.func2(...);