nodejs module.js:340 error: cannot find module

2020-05-19 18:09发布

I installed nodejs in C:\Program Files (x86)\nodejs

then I created a .js file and saved it in my desktop just to output 'hello world' in the console:

console.log('hello world');

When I tried to run the file from the command prompt:

C:\Users\Laura>cd desktop
C:\Users\Laura\Desktop>node nodeTest.js

I get:

module.js:340
throw err;
      ^
Error: Cannot find module 'C:\Users\Laura\Desktop\testNode.js'
at Function.Module._resolveFilename (module.js:338:15)
at Function.Module._load (module.js:280:25)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:901:3

I read many other related questions, and some of them recommend to run the install, and so I did.

C:\Users\Laura>npm install -g express

But no luck, still getting the same error message.

19条回答
Bombasti
2楼-- · 2020-05-19 18:49

Make sure you saved the file as JavaScript. Un check 'Hide extensions for all known type' check box in Folder Options window will show you the correct file extension(Folder>>view>>Option).

查看更多
对你真心纯属浪费
3楼-- · 2020-05-19 18:54

I think the issue is the NODE_PATH environment variable. I had the same problem but once I issued (on Windows)

set NODE_PATH=C:\Users\MyUser\node_modules

then all worked ok.

Cheers,

查看更多
虎瘦雄心在
4楼-- · 2020-05-19 18:54

I faced the same problem. I just copied the testNode.js file(that contain the test code) and pasted into the root of nodejs directory manually. I tried this command C:\Program Files (x86)\nodejs>node testnode.js Bingo! I received this message.

enter image description here

Then I typed this url in a browser and received the message "Hello World". Hope this help somebody.

查看更多
Deceive 欺骗
5楼-- · 2020-05-19 18:55

You need to:

  • Remove the tick of Hide extensions for known file types from Windows Explorer folders option
  • Your file will appear as testNode.js.txt
  • Remove the trailing .txt so as the file to be resolved as JS file

That's it, now it works!

查看更多
三岁会撩人
6楼-- · 2020-05-19 18:56

Restart your command prompt and check your path variable (type: path). If you can't find find nodejs installation dir from output add it to the path variable and remember to restart cdm again...

查看更多
▲ chillily
7楼-- · 2020-05-19 18:58

I was having the same problem with a server someone had written a while back. It turns out I didn't have a few things installed that the script required.

This question was helpful to me.

I ended up being able to use:

npm install yourMissingDependency 

Although in your instance it may just be a file that it doesn't have a path to. You could try putting that file in the same folder you are running the node script from.

查看更多
登录 后发表回答