我正在从头开始编写一个 Node 应用程序,其中包含以下 package.json,这是非常漂亮的样板文件。
{
"name": "myfirstnodeproject",
"version": "1.0.1",
"description": "Learning node",
"main": "index.js",
"start": "node server.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"license": "ISC",
"dependencies": {
"request": "^2.88.2"
}
}
我创建了server.js,如下所示:
var http = require("http");
http.createServer((inRequest, inResponse) => {
inResponse.end("Your IP Address is " + inRequest.connection.remoteAddress);
}).listen(9000);
当我使用 npm start
启动应用程序时,它运行良好。
然后,我创建了一个名为 server_time.js 的新文件:
require("http").createServer((inRequest, inResponse) => {
const requestModule = require("request");
requestModule(
"http://worldtimeapi.org/api/timezone/America/New_York",
function (inErr, inResp, inBody) {
inResponse.end(
`Hello from my first Node Web server: ${inBody}`
);
}
);
}).listen(9000);
我在 package.json 中更改了以下行:
"start": "node server_time.js",
但是,Node 似乎仍然选择了 server.js。我尝试了npm缓存验证、npm缓存清除-force、rm -rf node_modules、rm package-lock.json code> 和再次 npm install,但问题似乎并没有消失。我什至删除了 package.json 并重新定义了它,但是当我调用 npm start
时 start
的值仍然过时。
这是我的 shell 的输出:
GsMacbookPro:MyFirstNodeProject g$ cat package.json
{
"name": "myfirstnodeproject",
"version": "1.0.1",
"description": "Learning node",
"main": "index.js",
"start": "node server_time.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "G",
"license": "ISC",
"dependencies": {
"request": "^2.88.2"
}
}
GsMacbookPro:MyFirstNodeProject g$ ls
node_modules package-lock.json package.json server.js server_time.js
GsMacbookPro:MyFirstNodeProject g$ npm start
> <a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ef829689869d9c9b81808b8a9f9d80858a8c9bafdec1dfc1de" rel="noreferrer noopener nofollow">[email protected]</a> start /Users/g/Repos/MyFirstNodeProject
> node server.js
在有人问之前,node版本是v10.16.3,npm版本是6.9.0。
最佳答案
npm start
目前对您有用的原因是 npm
会根据包内容默认一些脚本值。
If there is a server.js file in the root of your package, then npm will default the start command to
node server.js
.
看这里:
所以你的 package.json
中的 start
字段实际上并没有做任何事情,因为它不在 scripts
下,这是它应该在的位置属于。
正确的方法是更新您的package.json
,使其如下所示:
{
"name": "myfirstnodeproject",
"version": "1.0.1",
"description": "Learning node",
"main": "index.js",
"scripts": {
"start": "node server_time.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "G",
"license": "ISC",
"dependencies": {
"request": "^2.88.2"
}
}
关于javascript - npm start 没有获取更新的 package.json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62353659/