节点安装钩子

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

钩子

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"]
}