NodeJS首次编写程序运行报错:Cannot find module问题求助
Hey there! I see you're running into a module not found error with your first Node.js program—don't worry, this is a super common issue for beginners, and it's almost never a problem with your code itself (which looks solid, by the way!).
Let's break down what's happening first. The error message you're seeing:
module.js:540 throw err;
^ Error: Cannot find module 'C:\Users\Daniel\Desktop\app'
at Function.Module._resolveFilename (module.js:538:15)
at Function.Module._load (module.js:468:25)
at Function.Module.runMain (module.js:684:10)
at startup (bootstrap_node.js:187:16)
at bootstrap_node.js:608:3
This tells us Node.js can't locate the file you're trying to run at the path C:\Users\Daniel\Desktop\app. Here are the most likely fixes to get you up and running:
Double-check your filename and file location
Make sure your code is saved in a file namedapp.jsdirectly on your Desktop. If you saved it under a different name (likeserver.jsorhello-world.js), Node won't find it when you run the command pointing toapp. Also double-check the file isn't accidentally saved in a different folder (like Documents or Downloads) instead of Desktop.Run the script from the correct directory
Typing full paths can lead to typos—instead, open your console and navigate to your Desktop first with this command:cd C:\Users\Daniel\DesktopThen run your script with:
node app.js(Swap
app.jswith your actual filename if you saved it under something else.) This is a simpler way to avoid path mistakes.Quick sanity check for Node.js installation
While this is less likely the issue here, you can confirm Node is working properly by runningnode -vin your console—this should print your installed Node version. If it doesn't, you might need to reinstall Node.js, but since the error is about locating a file, this is probably not the root cause.
Just to confirm, your code looks perfectly valid:
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!'); }); server.listen(port, hostname, () => { console.log('Server started on port '+port); });
Once you fix the path/filename issue, running this should start your server successfully—you'll see the "Server started on port 3000" message, and you can visit http://127.0.0.1:3000 in your browser to see the "Hello World!" response.
内容的提问来源于stack exchange,提问作者John Smith

