1. Read the error message!
Read the error message.
The first line of the second part says :
Error: Cannot find module 'C:\Users\User\Desktop\NodeJsProject\app.js'
So the first thing to check is: does the file exist?
On Windows, open a command prompt
(WinKey+r, type cmd
, press Enter). Run :
dir C:\Users\User\Desktop\NodeJsProject\app.js
If the response is – The system cannot find the path specified.
– or – File Not Found –
then you know that the file doesn't exist.
Likewise, on Linux/Unix (in my case MSYS2 on Windows), run
$ ls "C:\Users\User\Desktop\NodeJsProject\app.js"
ls: cannot access 'C:\Users\User\Desktop\NodeJsProject\app.js': No such file or directory
Thus, if on Linux you get No such file or directory, then you know
that the file doesn't exist.
2. Try running npm install
If Section 1 above didn't solve your problem, try running
npm install
, then npm start
.
If none of the above solved your problem, my last tip is to :
- delete the
node_modules
directory,
- delete the
package-lock.json
file,
- run
npm install
,
- run
npm start
.
4. If the error happens in VS Code
Note:
The error might occur for no apparent reason when debugging
in Visual Studio Code.
If you get the error inside VS Code, see if this answer
helps.
Presumably, you've already installed Node.js on your computer.
If not, download and install.
The error message is easy to reproduce.
After installing Node.js, open a command line, and run :
$ node thisFileDoesNotExist.js
node:internal/modules/cjs/loader:1078
throw err;
^
Error: Cannot find module 'C:\thisFileDoesNotExist.js'
[90m at Module._resolveFilename (node:internal/modules/cjs/loader:1075:15)[39m
[90m at Module._load (node:internal/modules/cjs/loader:920:27)[39m
[90m at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)[39m
[90m at node:internal/main/run_main_module:23:47[39m {
code: [32m'MODULE_NOT_FOUND'[39m,
requireStack: []
}
Node.js v18.14.2
6. How to run node <someFile.js>
without an error
To run Node.js in the terminal without an error,
in the Windows command line, run :
echo console.log('\nHello world!')> hello.js
node hello.js
In a Linux terminal, try:
echo "console.log('\nHello world\!\n')"> hello.js
node hello.js
In both cases, expect the response to be :
Hello world!
If you delete hello.js
, and then run node hello.js
, you should
once again get the error you asked about.
References