Npm start 与节点 app.js

我对 Node 非常陌生,并试图理解应用程序的基本知识。我很好奇为什么这两个命令:

Node app.js

—— VS ——

NPM 开始

输出相同的东西到控制台,并显示继续“监听”,但是为什么当我尝试访问 http://localhost:3000时,我只在运行第一个命令时得到一个404。

我看到 Express4似乎有一个不同的应用程序结构,但为什么一个成功地监听,而另一个没有,尽管相同的行为在控制台?

任何解释都是有帮助的。谢谢!

113271 次浏览

The two of these commands aren't necessarily the same. npm start runs whatever the 'start' script config says to run as defined in your 'package.json', node app.js executes the 'app.js' file in 'node'. See http://browsenpm.org/package.json for more info. So if you had the following package.json then the commands are completely different.

{
"name": "my cool node project",
....
"scripts": {
"start": "node index.js"
}
....
}

The following package.json is what you'll want to make them identical.

{
"name": "my cool node project",
....
"scripts": {
"start": "node app.js"
}
....
}

I'd start by checking what the 'start' script is set to run and try running the same command directly in your CLI rather than through NPM to see where the difference is.

but why is it that one successfully listens and the other doesn't

If the server is returning a 404 this would suggest the server is listening, but either the document root or access permissions aren't being setup properly so it returns a 'File not Found' response.

In addition to above answer I'd like to add a point:

Doing npm start without having scripts portion in your package.json will result in npm looking for server.js in that directory, if found run it using node server.js else it'll throw npm ERR! missing script: start as the error message.

Documentation: npm-start

Few more things I would like to add, may help future audience

First of all

Node - is run time for any javascript code

NPM is package manger, which can be used to download/update/run packages and many more, consisting of 3 things

  1. Website
  2. npm CLI
  3. the registry

Read here to see what everything it does for you.

node any.js - this will simply run the javascript file "any,js". So if there is no code in there to start a server, you will get error

npm start - will run the start command in the package.json. For very basic example if below is the start script in your package.json

enter image description here

It will simply print "Hello" on console.

if you create react app using CRA, you will usually have "react-scripts start" in this section. Which sets up the development environment and starts a server, as well as hot module reloading

That is the reason you donot get error in this case