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, but is only an example).
I think that a way was to get the source file of library and include it into a module like that:
module.exports = function (name, cb) {
//source code of library
});
But I think is a wrong way.
How can I include external library to nodejs project to use it inside it with its functionality?
Thanks
Without exporting, a no elegant way is to copy past the entire library, in the bottom of your node file. nasty you may already thought about it. there is also a bad thing about that. you will not be able to reuse it in all different files.
The other way is to export the files along your workflow every time you need a function. And i think this is ok.
Otherwise to answer that, you can write the export this way:
you can do that with node. all of those are normal function declared this way:
this way you can write a quick script that parse all the file, and take out the definitions of the functions, if you can't do it manually. You can use regex, to speed up that. you need two patterns. the first for
function name(
and the second forname = function(
. Hope that was helpful!the question was more about if there is a way included with nodejs. There is none at the moment. it may be in the future. You may also see this How do I include a JavaScript file in another JavaScript file?. It may not help though.
When one
requires
a module on nodejs, the content ofmodule.exports
is returned. So, one can return a function (as you do on your example) or an object, as inSo that, in the requiring file, you can:
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: