Export and Require in Node JS

  • Everything you write in node is a module
  • You can export a function is a module using “module.exports”
  • You can use a exported module using “require”
  • Example below

MathsDemo.js

function add(a, b){
    return a+b;
}
function subtract(a,b){
    return a-b;
}
module.exports.add = add;

ExecuteMaths.js

mathObject = require("./MathsDemo.js");
var output =  mathObject.add(10,20);
console.log('Result is : '+output);

Output :

Example : Writing data to a file

const fs = require('fs');
fs.writeFile('myfile', 'Hello World', (error)=>{
    if(error) {
        console.log('Error while saving data');
    }
});

Example : Taking user input and storing data to file

const readline = require('readline'); //Read Line API
const fs = require('fs'); //File System API

const wirteToFile = (data) => {
    fs.writeFile('myfile', `${data}`, error => {
        if(error) {
            console.log('Data has been saved');
        }
    });
};

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

rl.question('Enter data ', (data) => {
  wirteToFile(data);
  rl.close();
});

Leave a Comment