Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to import JavaScript library from CDN links in a node.js script

I have a script called myscript.js. I execute the script usually using this command:

$ node myscript.js

How can I include the JStat Library via the CDN address in the script:

//cdn.jsdelivr.net/jstat/1.2.1/jstat.min.js
like image 733
neversaint Avatar asked Jul 06 '15 08:07

neversaint


People also ask

How will you import external libraries in node JS?

Command “require” is used in Node JS for import external libraries. Mentioned below is an example of this. “var http=require (“http”)” . This will load the library and the single exported object through the HTTP variable.

What is a CDN JavaScript?

A content delivery network (CDN) refers to a geographically distributed group of servers which work together to provide fast delivery of Internet content. A CDN allows for the quick transfer of assets needed for loading Internet content including HTML pages, javascript files, stylesheets, images, and videos.


1 Answers

There isn't any logic built into node's require to do this.

If you are certain that this library supports use on the server-side (not all libraries are "isomorphic", that is, usable on both client and server side), then you can download it and require it locally (require('./jstat.min.js')).

The best way would be to find it on npm and install it, like any other node module.

Note: There isn't really an advantage to using a cdn on the server side. The main use case for a cdn is providing a cacheable copy to users' browsers, but users' browsers won't be running node code.

like image 120
Matthew King Avatar answered Sep 21 '22 14:09

Matthew King