Windows Server 2008 R2 企业版
节点版本 12.13.1
节点窗口版本 1.0.0-beta.5
当我调用我的节点应用程序时,我需要将路径传递给特定的环境文件,而不是在代码中使用 require('dotenv') 来加载环境变量(例如从默认的 .env 文件)。这个环境文件是不同的,取决于应用程序是为哪个客户启动的(例如不同的数据库、路径、客户代码等)。
在 cli 中,我可以通过这种方式成功地做到这一点:
node --require dotenv/config bin/www dotenv_config_path=C:\projects\abc\env\XYZ.env
如您所见,我使用绝对路径作为 env 文件的位置,但它也适用于相对路径。我只是想消除这一点,因为我无法使用 node-windows 进行这项工作。
我正在尝试使用 node-windows 创建一个 Windows 服务包装器,该服务包装器调用我的节点应用程序并像上面的代码一样加载特定的 env 文件。到目前为止无法使其工作,在创建 Windows 服务后,它会在片刻后退出,这告诉我它缺少运行所需的环境变量。这意味着它无法加载找到环境文件。
这是我使用 node-windows 创建 Windows 服务的脚本:
#!/usr/bin/env node
// Usage:
// npm run install-win XYZ
// Notes:
// 1. Before creating the windows service, make sure to delete any previous files in the /bin folder (i.e. all files abcXYZ.*)
// 2. After creating the windows service, change the Log On account to the ******* user to avoid persmission issues when using paths on other production servers
const args = process.argv;
const codeclient = args[2];
const serviceName = `abc${codeclient}`;
const environmentPath = `C:\\projects\\abc\\abc-api\\env\\${codeclient}.env`; // Make sure to use the full absolute path here
const Service = require('node-windows').Service;
// Create a new service object
const svc = new Service({
name: serviceName,
description: serviceName,
script: require('path').join(__dirname, 'www'),
scriptOptions: `dotenv_config_path=${environmentPath}`,
nodeOptions: [
'--require=dotenv/config',
'--harmony',
'--max_old_space_size=4096'
]/*,
env: {
name: 'DOTENV_CONFIG_PATH',
value: environmentPath
}*/
});
// Listen for the "install" event, which indicates the
// process is available as a service.
svc.on('install', function(){
svc.start();
});
svc.install();
我已经在各种配置中尝试了“scriptOptions”方法和“env”方法,但没有任何效果。
如果以前有人设法制作过类似的东西,我非常想知道你是怎么做到的。