2

我正在使用一个文件中的一个函数,在另一个文件中,并在那里调用它。这导致该函数在从命令行运行时同时运行两次,但在我在 VSCode 中运行时却没有。

这是一个例子:

// fileOne

async function task() {
    console.log('Hello')
}

module.exports = { task }

// fileTwo
const fileOne = require('./fileOne');

fileOne.task();

在 VSCode 中运行时的输出:

Hello

在命令行中运行时的输出:

Hello
Hello

我不确定为什么会这样……不,我不是偶然在 fileOne 中调用它,因为那样它也会在 VSCode 中运行两次。

谢谢。

4

2 回答 2

1

如果您的fileOneandfileTwo看起来与您的问题陈述中的完全一样,即:

fileOne.js

async function task() {
    console.log('Hello')
}

module.exports = { task }

文件二.js

const fileOne = require('./fileOne');

fileOne.task();

当以下列方式运行时,输出为 1 个单一的“Hello”:

  1. 命令提示符中

    node fileTwo.js

  2. Windows PowerShell中

    node .\fileTwo.js

  3. Linux Bash 终端中

    $ nodejs fileTwo.js

如果您运行在 1 个文件中包含两个文件的脚本,这同样适用(正如您在评论中提到的那样)。



在某些情况下,Node.js 会打印输出两次,但这些是不同的场景。

您可以尝试fileTwo.js单独运行,但如前所述,它在公共文件下也能正常运行(例如my_program_here.js,如果它只是fileOne.jsand的组合fileTwo.js)。

于 2020-10-03T22:47:31.463 回答
0
const fileOne = require('./fileOne');

这基于不同命令行中的“./”。

于 2020-10-06T16:31:16.663 回答