how to import external library to nodejs

后端 未结 2 772
心在旅途
心在旅途 2021-01-07 06:40

I would like to know how can I import an external library to nodejs. For example I would like to have phanotmjs library (I know that arelady exist an npm to get phantomjs, b

2条回答
  •  囚心锁ツ
    2021-01-07 07:10

    When one requires a module on nodejs, the content of module.exports is returned. So, one can return a function (as you do on your example) or an object, as in

    in module.js:
    
    module.exports={
        func:function(){ return true; },
        val:10,
        ...
    }
    

    So that, in the requiring file, you can:

     var m=require('module');
    
     assert(m.func()===true);
     assert(10===m.val);
    

    This is explained in the nodejs documentation under Modules

    So if you have an external JS library that exposes three functions: a, b, and c, you might wrap them as:

    module.exports={
        exportedA:lib.a,
        exportedB:lib.b,
        exportedC:lib.c
    };
    
    lib.a=function(){ ... };
    
    lib.b=function(){ ... };
    
    lib.c=function(){ ... };
    

提交回复
热议问题