Search code examples
javascriptnode.js

Module Not Found Error while trying to run Hello World program in node.js


Tried executing myfirst.js program from the terminal (Directory/command mentioned below). I was expecting a run window or a browser popup.

Typed node myfirst.js in the terminal while being in the same directory. The error I get:

node:internal/modules/cjs/loader:1147
  throw err;
  ^

Error: Cannot find module 'C:\Users\{UserName}\myfirst.js'
    at Module._resolveFilename (node:internal/modules/cjs/loader:1144:15)
    at Module._load (node:internal/modules/cjs/loader:985:27)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:135:12)
    at node:internal/main/run_main_module:28:49 {
  code: 'MODULE_NOT_FOUND',
  requireStack: []
}
Node.js v20.11.1

Exact directory\command: C:\Users\{UserName}>node myfirst.js

Path where node is installed: C:\Program Files\nodejs

Path of file: C:\Users\{UserName}\myfirst.js


Solution

  • Check to make sure that the file is not saved as a text file (.txt), such that it would actually be myfirst.js.txt. Node can parse text files, so running node myfirst.js.txt would work in that case. This also applies to files that don't have an extension, as in myfirst instead of myfirst.js.

    I would recommend using Visual Studio Code as an environment, as it has syntax highlighting and a built in terminal, which can be invaluable for learning to code.