Command line "node index.js" does not output correctly on windows 10, how to make it work?

Viewed 1332

SOLUTION: I found the solution to my problem, it was wrongly encoded. I created the file in the terminal (just to test around what the terminal can do), and it encoded it wrongly. I just created a new file and tried out console.log("Hello"); and that worked out GREAT in the terminal.

PROBLEM: I've installed Node.js yesterday while following a tutorial on it, and when I tried to run the command node index.js I get the following inside my terminal:

$ node index.js
C:\Users\NAME\Desktop\intro-to-node\index.js:1
��c


SyntaxError: Invalid or unexpected token
?[90m    at wrapSafe (internal/modules/cjs/loader.js:1053:16)?[39m
?[90m    at Module._compile (internal/modules/cjs/loader.js:1101:27)?[39m
?[90m    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1157:1
0)?[39m
?[90m    at Module.load (internal/modules/cjs/loader.js:985:32)?[39m
?[90m    at Function.Module._load (internal/modules/cjs/loader.js:878:14)?[39m
?[90m    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_ma
in.js:71:12)?[39m
?[90m    at internal/main/run_main_module.js:17:47?[39m

I've also followed this guide here: https://nodejs.org/download/release/v12.18.3/docs/api/synopsis.html I copied the content of the code into my file as well, but regardless I get the same output in my terminal.
At first I had console.log("Hello World"); and then I tried it with:

const http = require('http');

const hostname = '127.0.0.1';
const port = 3000;

const server = http.createServer((req, res) => {
  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/plain');
  res.end('Hello, World!\n');
});

server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});

I am using Git Bash as a Terminal, but the same happened with MS PowerShell and CMD. I am on Windows 10, the latest update as well. Node Version is v12.18.3. It's also inside the PATH, node -v works fine and I get the version number as well, so does node -i.

3 Answers

I think you really have some special characters in the file. Please copy the exact character �� and find in the editor you are using.

SOLUTION: I found the solution to my problem, it was wrongly encoded. I created the file in the terminal (just to test around what the terminal can do), and it encoded it wrongly. I just created a new file and tried out console.log("Hello"); and that worked out GREAT in the terminal.

You are trying to create a server using http.createServer, but it's not imported into the file. Please require it as below.

const http = require("http");

This will solve your issue

Related