Syntax Error: Invalid or Unexpected Token when running a nodejs file using Visual Studio Code (Using powershell)

Viewed 4005

I've been trying to look for a solution but I can't seem to find one. I am a beginner to nodejs and basically I have created a new nodejs file called "app.js" inside of a directory called "HelloNode". When I use "node app.js" inside of powershell, the terminal tells me this:

This is the image of my screen

Code in VS Code:

var msg = "hello world";
console.log(msg);

Output in terminal:

PS C:\Users\yanab\HelloNode> node app.js
C:\Users\yanab\HelloNode\app.js:1
��v


SyntaxError: Invalid or unexpected token
    at wrapSafe (internal/modules/cjs/loader.js:1001:16)
    at Module._compile (internal/modules/cjs/loader.js:1049:27)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1114:10)
    at Module.load (internal/modules/cjs/loader.js:950:32)
    at Function.Module._load (internal/modules/cjs/loader.js:791:14)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12)
    at internal/main/run_main_module.js:17:47

Solutions I have tried:

  • Tried to change environment variable
  • Used the nodejs correct version using nvm use 'version number'

Notes:

  • Using a combination of Visual Studio Code and nvm
  • After searching for a while it might have something to do with UTF-16 encoding and how it isn't in UTF-8 encoding but I may be wrong.

Solution: Well I basically just made the file inside of vscode by right click -> new file and it worked. What I did before was use powershell and the command echo to make a new file. Don't understand what happened but making the file inside of vscode seems to be the solution.

4 Answers

I had the same situation. It turns out the file was UCS-2 encoded. After converting it to UTF-8 using notepad ++, it started working fine.

In my case, the reason for the UCS-2 encoding was the way I was filling out the file: echo 'console.log("Hollow world");' > test.js

same problem here. I created file via powershell echo command. My solution is reopen my computer and create file without command line. :$

This is an error that appears when there is some enexpected syntax when running javascript.

at wrapSafe (internal/modules/cjs/loader.js:1001:16)
at Module._compile (internal/modules/cjs/loader.js:1049:27)

This second line says that this error appeared while compiling the code file. (even though javascript is not a compiled language). The same error appears for the following code(it wont even console log):

console.log('running code');
2q307qwekfjn;

So there is some error in the formatting of your file, some unexpected symbol(the ??v symbol) added by the ide or when saving etc.

The problem is with syntax, ’’ replace with '', usually few editors like the apple note program use ’ instead of ' and when you copy-paste, it won't compile.

Related