首页 > 解决方案 > 如何以编程方式删除 npm 包?

问题描述

我希望能够在运行时在 node.js 应用程序中动态添加和删除 npm 包。使用安装包可以npm.install(...)正常工作,但npm.remove(...)只是从文件系统中删除包,但代码中仍然需要实际模块。我尝试清除 npm 缓存和各种模块,decache但不是运气。如何以编程方式删除包?

下面的代码以“commander”包为例说明了我的过程。

 const npm = require("npm");
 const assert = require("assert");

 const name = "commander";

 npm.load({}, error => {

   try{
     console.log(require(name));

   } catch(e){
     console.log("not available - good");
   }
    //install the package
    npm.install(name,  (error, data) => {

      console.log("error install",error);
      assert(require(name) != null)  

      //remove the package
      npm.remove(name,  (error, data) => {  

        console.log("error remove",error);
        require.cache = {};

        //still here, even so the files have been removed from the FS
        console.log(require(name));
      })

    });    


 });

标签: javascriptnode.jsnpmnode-modulesnpm-install

解决方案


推荐阅读