简体   繁体   中英

JavaScript Function Not Logging Anything to the Terminal in Visual Studio Code

I've tried to run the function this way:

function helloWorld() {
    console.log("Hello World!");
}

helloWorld()

在此处输入图片说明

And I've tried to run the function this way:

function helloWorld() {
    let text = "Hello World!";
    console.log(text);
}

helloWorld()

在此处输入图片说明

But either way, nothing is getting logged to the terminal. The first way is giving me a syntax error:

syntax error near unexpected token 'helloWorld'

Can anyone please help me understand why I'm not able to run a simple function in the terminal in Visual Studio Code?

Thank you

EDIT : Added helloWorld() to the bottom of the file.

The file is sitting on my desktop. I tried to enter:

myName-MBP:~ myName$ node </desktop/index.js>

and this returned:

bash: syntax error near unexpected token 'newline'

在此处输入图片说明

EDIT 2 : The problem was initially solved, but then I started getting this error when running node commands:

internal/modules/cjs/loader.js:582
    throw err;
    ^

Error: Cannot find module 'C:\Users\User\Desktop\NodeJsProject\app.js'
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:580:15)
    at Function.Module._load (internal/modules/cjs/loader.js:506:25)
    at Function.Module.runMain (internal/modules/cjs/loader.js:741:12)
    at startup (internal/bootstrap/node.js:285:19)
    at bootstrapNodeJSCore (internal/bootstrap/node.js:739:3)

As is described in this article . I already had node installed on my system.

And what helped me to fix that issue ^ was to create a new folder on my desktop, place the .js file inside of that folder, open that folder within VS Code, and then type node index.js in the terminal.

Do you have nodejs installed? If yes, then you can type node <filepath> where filepath is a path to your file and execute the JavaScript file.

Let's say if your file is called script.js then try typing node script.js to the terminal and see if that helps. Also, make sure your shell is in the current directory.

JavaScript cannot be executed directly in the bash shell. You need nodejs to execute it.

As arfat's answer states, you can run the code with Node.js in the terminal: $ node /desktop/index.js .

Alternatively, you could install the vscode extension Code Runner . This makes it easy to see console logs in the OUTPUT tab with a keyboard shortcut: Ctrl+Alt+N .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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