简体   繁体   English

使用Node JS命令行从另一个文件执行功能

[英]Executing a function from another file using Node JS Command Line

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 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). 我试图用var exports.connector = function connector(args) {在B.js,然后require在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代码?

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: 使用..来建立目录,因此,例如,如果您的基本目录的目录“服务器”的目录为“ A.js”,目录“脚本”的目录为“ 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(...);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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