Reputation: 4101
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.
Upvotes: 2
Views: 1893
Reputation: 1300
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
.
Upvotes: 1
Reputation: 171
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.
Upvotes: 3