Learn Simpli

Free Online Tutorial For Programmers, Contains a Solution For Question in Programming. Quizzes and Practice / Company / Test interview Questions.

Node module system

The node module system allows developers to load node modules that are installed by npm. And also node module system allows loading the library that has been developed by its own developers or any the external third API libraries.

Node module system node js

Any modules can be loaded into our functionality by using require() method in node js. The require() scans the entire node_modules directory and imports or loads the specified library. Let’s take an example fs file server.

Importing the node modules:

Create a file called server.js and put the following code and run the command: node server.js
Reading the file:

// import fs
const fs = require('fs');

// reading the file
const fileData = fs.readFileSync('users.json', 'utf8');
if (fileData) {
    console.info(fileData);
} else {
    console.log('File is empty....');
    return false;
}

// output
{
    "users": [
        {
            "id":1,
            "name":"John"
        },
        {
            "id":2,
            "name":"Jack"
        }
    ]
}

Writing the file:

// import fs
const fs = require('fs');

// writting the file
let employee = {
    'users': [
        {
            'id':1,
            'name':'John'
        },
        {
            'id':2,
            'name':'Jack'
        }
    ]
}
 
var fileContent = JSON.stringify(employee); 
fs.writeFile('usersNew.json', fileContent, 'utf8', function (err) {
    if (err) {
        console.log('Couldnot create the file');
        return console.log(err);
    }
    console.log('Employee files has been created.');
});

//output
Employee files has been created.

Importing our owner modules:
Create a file user.service.js and put the below code

user.service.js

module.exports.printUser = (param) => {
        console.log(`Hi ${param} how are you doing?`);
}

server.js

const userService = require('./user.service');
userService.printUser('John');

Run the command: node server
//output
Hi John how are you doing?

One thought on “Node module system node js

Comments are closed.