为什么我的函数在命令行中运行两次但在vscode中没有运行

问题描述

我正在使用一个文件中的功能,另一个文件中的功能,并在那里调用它。这导致该函数从命令行运行时同时运行两次,而不是在VSCode中运行时。

这里是一个例子:

// fileOne

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

module.exports = { task }

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

fileOne.task();

在VSCode中运行时的输出

Hello

在命令行中运行时的输出

Hello
Hello

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

谢谢。

解决方法

如果您的fileOnefileTwo与问题陈述中的显示完全相同,即:

fileOne.js

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

module.exports = { task }

fileTwo.js

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

fileOne.task();

通过以下方式运行时,输出为1个单个“ Hello”:

  1. 命令提示符

    node fileTwo.js

  2. Windows PowerShell

    node .\fileTwo.js

  3. Linux Bash Terminal

    $ nodejs fileTwo.js

如果您运行两个文件都在1个文件之内的脚本(如注释中所述),同样如此。



在某些情况下,Node.js会print the output twice,但那是不同的情况。

您可以尝试仅单独运行fileTwo.js,但是如上所述,它在一个通用文件(例如,您的my_program_here.jsfileOne.js的组合下也可以很好地工作)和fileTwo.js)。

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

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