Node.js – Error ‘console’ is undefined

I just installed Node.js on a new system and wanted to make sure it worked. I tested it with a simple hello world script.

Contents of the node.js file
console.log("Hello node");

Then I attempted to run it:
C:\>node node.js

Which produced the following error:
Script: C:\node.js
Line: 1
Char: 1
Error: 'console' is undefined
Code: 800A1391
Source: Microsoft JScript runtime error

Weird. And Microsoft JScript runtime? Very weird.

Turns out, Windows is trying to run the Javascript, node.js, not via Node.js but natively in Windows.

If I rename the file hellonode.js I can reproduce the same error:
C:\>hellonode

Or I can run the intended file via Node.js:
C:\>node hellonode.js
Hello node

I did not realize that the Windows command prompt could/would execute Javascript files natively.

6 thoughts on “Node.js – Error ‘console’ is undefined”

  1. The problem is not the name of the file, the problem is your node installation. Check if your computer environment variables contains the path for the node.exe file.

  2. @Gregory, I beg to differ. The issue is specifically about the Windows path and not the Node.js installation.

    The Microsoft docs on start indicate that:

    When you run a command that uses a first token that does not contain an extension, Cmd.exe uses the value of the PATHEXT environment variable to determine which extensions to look for and in what order.

    On my current Windows 10 box, my PATHEXT includes .JS:

    echo %PATHEXT%
    .COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC

    From this Microsoft document on Windows path:

    The current directory is always searched before the directories specified in the command path.

    Based on this information, Windows must find and run the node.js file in the current working directory rather than the C:\Program Files\nodejs\node.exe.

    If you are seeing something different, let me know!

Leave a Reply

Your email address will not be published. Required fields are marked *