有没有办法从nodejs代码中的package.json获取版本?
有没有办法在nodejs应用程序中的package.json
中设置版本?我想要这样的东西
Is there a way to get the version set in package.json
in a nodejs app? I would want something like this
var port = process.env.PORT || 3000
app.listen port
console.log "Express server listening on port %d in %s mode %s", app.address().port, app.settings.env, app.VERSION
我发现以下代码片段最适合我.由于它使用require
加载package.json
,因此无论当前工作目录如何,它都可以工作.
I found that the following code fragment worked best for me. Since it uses require
to load the package.json
, it works regardless the current working directory.
var pjson = require('./package.json');
console.log(pjson.version);
由@Pathogen提供的警告:
使用Browserify进行此操作会带来安全隐患.
注意不要将package.json
公开给客户端,因为这意味着所有依赖项版本号,构建和测试命令以及更多信息都将发送给客户端.
如果要在同一项目中构建服务器和客户端,则也要公开服务器端版本号. 攻击者可以使用此类特定数据来更好地适应您服务器上的攻击.
Doing this with Browserify has security implications.
Be careful not to expose yourpackage.json
to the client, as it means that all your dependency version numbers, build and test commands and more are sent to the client.
If you're building server and client in the same project, you expose your server-side version numbers too. Such specific data can be used by an attacker to better fit the attack on your server.