0

I've noticed that every time I want to use a package in Node I need to "npm install" it locally and then use the require keyword. I wanted to know if there's a way I could include a remote library kind of like that way we can include remote files using client side html when we use a CDN:

<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
</head>
Shai UI
  • 50,568
  • 73
  • 204
  • 309

3 Answers3

0

require() in node core is synchronous, so there is no way to do it natively (since network i/o is async in node). You'd have to write some function to fetch the resource first and then require() it.

mscdex
  • 104,356
  • 15
  • 192
  • 153
0

You can't actually supply a URL to "require", but you can of course fetch a remote resource from a URL, including a javascript resource. And then load it locally.

The following answer even links to a "remote_require" that someone wrote to do another kludgy version of this.

how to require from URL in Node.js

Community
  • 1
  • 1
Jason Loveman
  • 675
  • 6
  • 5
-1

If you are trying to use other JavaScript files in your application, you will need to export all of the functions defined by those JavaScript files.

You would export a function like so:

exports.nameOfExport = function(x, y, z) {
// Function content
};

You would then require this file in the file you are trying to use it in with this line:

var myFileName = require('./routes/folder1/myFileName'); // Relative path to required file

If this doesn't answer your question, I suggest going to https://www.npmjs.org/ to search for a package that does what you are trying to do.

Lethal Left Eye
  • 368
  • 2
  • 9
  • 17