To include external libraries in Java, we use import statement.
In node.js, we use require keyword. For example,
var http = require(‘http’);
We can also include relative files as shown below:
var myFile = require(‘./myFile’); // loads myFile.js
To install modules from npm(node package manager),
$ npm install express
Modules aren’t automatically injected into the global scope, but instead you just assigned them to a variable of your choice.
You can create your own module as well.
- The first approach would be to export a single object:
var person = { name: ‘John’, age: 20 };
module.exports = person;
- The second approach requires adding properties to the
exports
object:
exports.name = ‘John';
exports.age = 20;
Modules don’t share scope, so if you want to share a variable between different modules, you must include it into a separate module that is then required by the other modules. And also modules are loaded once and then are cached by node.
ProsperaSoft offers Node.js development solutions. You can email at info@prosperasoft.com to get in touch with ProsperaSoft Node.js experts and consultants.