节点安装钩子

Node安装钩子允许在安装新npm模块(包括节点模块和外部模块)时添加自定义代码。

Hooks

preInstall

在运行npm install安装npm模块之前调用。

该钩子接收一个InstallEvent对象,其中包含有关待安装模块的信息。

{
    "module": "<npm module name>",
    "version": "<version to be installed>",
    "url": "<optional url to install from>",
    "dir": "<directory to run the install in>",
    "isExisting": "<boolean> this is a module we already know about",
    "isUpgrade": "<boolean> this is an upgrade rather than new install",
    "args": [ "an array", "of the args", "that will be passed to npm"]
}

该钩子可以修改InstallEvent来改变npm的运行方式。例如, 可以修改args数组来改变传递给npm的参数。

如果钩子返回false,将跳过npm install步骤,并继续执行后续流程,就像已经运行过安装一样。这允许使用某些替代机制——只要最终结果是将模块安装到预期的node_modules目录下即可。

如果钩子抛出错误,安装将干净利落地失败。

RED.hooks.add("preInstall", (installEvent) => {
    console.log(`About to install ${installEvent.module}@${installEvent.version}`);
});

postInstall

npm install完成安装npm模块后调用。

注意 如果 preInstall 钩子返回了 false,则不会运行 npm install,但这个钩子仍会被调用。

该钩子可用于运行任何所需的安装后活动。

例如,在Electron环境中运行时,需要重新构建模块:

RED.hooks.add("postInstall",  (installEvent, done) => {
    child_process.exec("npm run rebuild " +  installEvent.module,
        {cwd: installEvent.dir},
        (err, stdout, stderr) => {
            done();
        }
    );
});

如果钩子抛出错误,安装将干净利落地失败。

如果前面的npm install返回了错误,则不会调用此钩子。

preUninstall

在运行npm remove卸载npm模块之前调用。

该钩子函数接收一个UninstallEvent对象,其中包含有关待移除模块的信息。

{
    "module": "<npm module name>",
    "dir": "<directory to run the remove in>",
    "args": [ "an array", "of the args" , "we will pass to npm"]
}

该钩子可以修改UninstallEvent来改变npm的运行方式。例如, 可以修改args数组来改变传递给npm的参数。

如果钩子返回false,则会跳过npm remove操作,流程会继续执行,就像已经运行过该操作一样。这允许使用某些替代机制。

如果钩子抛出错误,卸载将干净利落地失败。

RED.hooks.add("preUninstall", (uninstallEvent) => {
    console.log(`About to remove ${uninstallEvent.module}`);
});

postUninstall

npm remove完成移除npm模块后调用。

注意 如果 preUninstall 钩子返回了 false,则不会执行 npm remove 命令,但这个钩子仍会被调用。

该钩子可用于运行任何所需的卸载后活动。

如果钩子抛出错误,它将被记录,但卸载仍会顺利完成,因为在npm remove完成后我们无法回滚操作。

RED.hooks.add("postUninstall",  (uninstallEvent) => {
    console.log(`Removed ${uninstallEvent.module}`);
});

事件对象

InstallEvent 对象

{
    "module": "<npm module name>",
    "version": "<version to be installed>",
    "url": "<optional url to install from>",
    "dir": "<directory to run the install in>",
    "isExisting": "<boolean> this is a module we already know about",
    "isUpgrade": "<boolean> this is an upgrade rather than new install",
    "args": [ "an array", "of the args", "we will pass to npm"]
}

UninstallEvent 对象

{
    "module": "<npm module name>",
    "dir": "<directory to run the remove in>",
    "args": [ "an array", "of the args", "we will pass to npm"]
}