Why is my function running twice in command line but not in vscode

1.1k views Asked by At

I am using a function from one file, in another file, and calling it there. This is causing the function to run twice at the same time when run from the command line, but not when I run it in VSCode.

Here is an example:

// fileOne

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

module.exports = { task }

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

fileOne.task();

Output when ran in VSCode:

Hello

Output when ran in Command Line:

Hello
Hello

I'm not sure why this is happening... No I am not calling it in fileOne by accident because then it would also run twice in VSCode.

Thanks.

2

There are 2 answers

0
colourCoder On

If your fileOne and fileTwo look exactly as in your problem statement, i.e.:

fileOne.js:

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

module.exports = { task }

fileTwo.js:

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

fileOne.task();

the output is 1 single 'Hello' when run in the following ways:

  1. in Command Prompt

    node fileTwo.js

  2. in Windows PowerShell

    node .\fileTwo.js

  3. in Linux Bash Terminal

    $ nodejs fileTwo.js

The same applies if you run the script having both files within 1 file (as you mention in the comments).



There were some cases where Node.js would print the output twice, but those were different scenarios.

You can try running just the fileTwo.js separately, but as already mentioned, it worked well also under a common file (e.g. your my_program_here.js in case it is just a combination of fileOne.js and fileTwo.js).

1
thelovekesh On
const fileOne = require('./fileOne');

This is based on the './' in different command lines.