【问题标题】:Is there a cross-platform way to get the name of the parent process in Node.js?有没有一种跨平台的方式来获取 Node.js 中父进程的名称?
【发布时间】:2021-09-09 00:09:51
【问题描述】:
我正在开发一个 npm 包初始化程序,即当用户运行 npm init <my-package-initializer> 命令时运行的程序。
npm 不再是 Node.js 的唯一包管理器,yarn 也很受欢迎,pnpm 是我个人的最爱,我想支持这三个。简单的方法是询问用户他们更喜欢哪个包管理器,或者提供一个命令行开关,例如CRA does。
但是用户已经通过运行 yarn create 而不是 npm init 来表明他们的偏好。再问就觉得烦。我们可以检查yarn 或pnpm 是否是我们的父进程。
是否有跨平台的方式来获取这些信息?
【问题讨论】:
标签:
node.js
npm
yarnpkg
pnpm
【解决方案1】:
对于未来的 googlers,我最终使用了以下 sn-p。我使用它来选择默认选项,但我仍然明确询问用户他们的包管理器偏好,比抱歉更安全。
function getPackageManager() {
// This environment variable is set by npm and yarn but pnpm seems less consistent
const agent = process.env.npm_config_user_agent;
if (!agent) {
// This environment variable is set on Linux but I'm not sure about other OSes.
const parent = process.env._;
if (!parent) {
// No luck, assume npm
return "npm";
}
if (parent.endsWith("pnpx") || parent.endsWith("pnpm")) return "pnpm";
if (parent.endsWith("yarn")) return "yarn";
// Assume npm for anything else
return "npm";
}
const [program] = agent.split("/");
if (program === "yarn") return "yarn";
if (program === "pnpm") return "pnpm";
// Assume npm
return "npm";
}