nodejs中判断windows、mac或linux系统

const os = require('os');

if (os.type() == 'Windows_NT') {
	//windows平台
}
if (os.type() == 'Darwin') {
	//mac
}
if (os.type() == 'Linux') {
	//Linux平台
}

window和linux已验证通过,mac待验证

通过当前系统(win,linux)配置文件路径

 utils/index.js:

const os = require("os");
const path = require("path");

/**
注意:开发环境时用【process.cwd()】,方便调试,
当打包生产环境(win,linux)时需要将所有的【process.cwd()】换成【process.execPath,"../"】,
因为linux中的process.cwd()只表示当前路径,若在当前路径执行其他路径下的node服务,路径将会出错!
而用【process.execPath,"../"】的话可以直接拿到node服务所在路径
 * 
 */
// 通过当前系统(win,linux)配置文件路径
let setPathByOs = function (fileName = "") {
  var configPath = "";
  if (os.type() == "Windows_NT") {
    configPath = path.resolve(process.cwd(), fileName);
  }
  if (os.type() == "Linux") {
    configPath = path.resolve(process.execPath, "../", fileName);
  }
  return configPath;
};

module.exports = {
  setPathByOs,
};

app.js中使用:

相对根目录而言 

let { setPathByOs } = require("./utils/index.js");


const configPath = setPathByOs("./config_node.json");

猜你喜欢

转载自blog.csdn.net/qq_40323256/article/details/129800021