Third party modules and libraries
You can load third-party Common.js-type modules using the require() function.
Load an external module in one of the following ways:
| Method |
Description |
| Load a single file
|
Load a single file written in Common.js format by copying the file into the script folder and requiring it. The standard Node.js require functionality is used.
Example:
If the file is myLibrary.js and it is in the script folder, add the following lines to the script:
const myLibrary = require('./myLibrary.js');
myLibrary.myFunc1();
myLibrary.js then contains:
module.exports = {
myFunc1(){
},
…
Example:
For a JSON file, add the following lines to the script:
const someData = require('data.json');
load.log(someData.age); //prints 36 to the log
data.json then contains:
{
"user":"bob",
"age":36
}
|
| Load an npm module
|
Load any npm module that runs within Node.js. To use this method, Node.js must be installed on your computer.
For example, use the following procedure to install the lodash library:
-
Open the command prompt and navigate to the script folder.
-
Type npm install lodash and wait for the process to finish. The node_modules folder is created in the script folder.
-
In your script, add the following line (do not add the .js extension):
const lodash = require('lodash');
Tip: If Node.js is not installed, you can download an npm module using standalone npm or using a third-party package manager such as Yarn.
|
|
Manage multiple modules via package.json
(Advanced use case)
|
If you are using multiple third-party npm modules and want to manage their dependencies, you can create a package.json file and manage all the dependencies with npm.
To use this method, Node.js must be installed on your computer.
-
Create the package.json file using the npm init command as follows:
-
Open the command prompt and change to the script folder.
-
Type npm init --yes and wait for the process to finish.
-
To install any supported package, type npm install <packagename> and wait for the process to finish. The node_modules folder is created in the script folder.
-
In your script, add the following line (do not add the .js extension):
const <packagename> = require('<packagename>');
Tip: If Node.js is not installed, you can download an npm module using standalone npm or using a third-party package manager such as Yarn.
|
Back to top