我使用 gulp-nodemon
因为它的实用程序最明显。
Nodemon is a utility that will monitor for any changes in your source and automatically restart your server.
但我不理解在express/node开发中似乎普遍存在的做法。
我刚刚开始使用 Node 和 Express,但据我了解:
app.js
var express = require('express'),
app = express(),
port = process.env.PORT || 8016;
app.get('/', function rootHndlr(req, res) {
/* body... */
res.send('welcome to my API!');
});
app.listen(port, function listenHndlr(){
console.log('Gulp is running my app on PORT ' + port);
});
如果未设置,则将端口设置为8016
。
端口 = process.env.PORT || 8016;
现在我们绑定(bind)并监听指定主机和端口上的连接。
但是后来我看到人们在 gulp 任务中将以下内容配置到 gulpfile.js 中的 nodemon
gulpfile.js
var gulp = require('gulp'),
nodemon = require('gulp-nodemon');
gulp.task('default', function() {
// content
nodemon({
script: 'app.js',
ext: 'js'
env: {
PORT: 8000
},
ignore: ['./node_modules/**']
}).
on('restart', function(){
consile.log('Restarting');
});
});
正如您可以使用nodemon
中的值之一env:{PORT:8000}
为什么要再次设置端口?
谢谢!
最佳答案
人们正在使用类似的东西作为后备:port = process.env.PORT || 8016;
您的应用程序应该足够灵活,并通过传递环境变量来使其监听另一个端口。一般来说,这就是环境变量的目的。
关于你的例子,我认为编写这个 gulpfile 的人想让应用程序监听端口 8000 是有原因的。我想说,只要你 100% 确定应用程序没有理由需要在端口 8000 上运行(例如,它位于将流量转发到端口 8000 的反向代理后面),那么更改该值或删除 PORT: 8000
是安全的。
关于node.js - 在gulp-nodemon中设置端口有什么用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40046292/