Understanding the npm - Node module system


In our earlier example of getting user input and storing it a file has only one file. But in real life scenarios, we will have to create multiple file to keep code simple and easy to read.

Let’s see how to use module system in node.js

We have App.js −

const http = require('http');
const fs = require('fs');
const server = http.createServer((req, res)=>{
   const url = req.url;
   if(url === '/'){
      res.write('<html>');
      res.write('<head> <title> Hello TutorialsPoint </title> </head>');
      res.write(' <body> <form action="/username" method="POST"> <input type="text" name="username"/>       <button type="submit">Submit</button> </body>');
      res.write('</html>');
      return res.end();
   }
   if(url === '/username' && req.method === 'POST'){
      const requestBody = [];
      req.on('data', (chunks)=>{
         requestBody.push(chunks);
      });
      return req.on('end', ()=>{
         const parsedData = Buffer.concat(requestBody).toString();
         const username = parsedData.split('=')[1];
         fs.writeFile('username.txt', username, (error)=>{
            console.log(error);
         });
         //redirect
         res.statusCode=302;
         res.setHeader('Location','/');
         return res.end();
      });
   }
   res.write('<html>');
   res.write('<head> <title> Hello TutorialsPoint </title> </head>');
   res.write(' <body> Hello </body>');
   res.write('</html>');
   res.end();
});
server.listen(3000);

Create a separate file routes.js −

Move the code from createServer method to routes.js file.

const url = req.url;
if(url === '/'){
   res.write('<html>');
   res.write('<head> <title> Hello TutorialsPoint </title> </head>');
   res.write(' <body> <form action="/username" method="POST"> <input type
   ="text" name="username"/> <button type="submit">Submit</button> </body>');
   res.write('</html>');
   return res.end();
}
if(url === '/username' && req.method === 'POST'){
   const requestBody = [];
   req.on('data', (chunks)=>{
      requestBody.push(chunks);
   });
   return req.on('end', ()=>{
      const parsedData = Buffer.concat(requestBody).toString();
      const username = parsedData.split('=')[1];
      fs.writeFile('username.txt', username, (error)=>{
         console.log(error);
      });
      //redirect
      res.statusCode=302;
      res.setHeader('Location','/');
      return res.end();
   });
}
res.write('<html>');
res.write('<head> <title> Hello TutorialsPoint </title> </head>');
res.write(' <body> Hello </body>');
res.write('</html>');
res.end();

Add an import statement for file system module in routes.js file and remove the import from App.js file as we won’t be using it there now.

Above code in file routes.js should be inside a JavaScript function like below −

const requestHandler = (req, res)=>{ --routes.js file code-- }
get the url and method data from request is same in routes.js.
const url = req.url;
const method = req.method;

With these changes, we can write an export for routes.js file.

module.exports = requestHandler;

module.exports can have multiple key value pair exports like below −

module.exports = {
   key1: value1,
   key2: value2
}

Import the routes.js file in App.js file.

const routes = require('./routes');

Updated App.js file is now −

const http = require('http');
const routes = require('./routes');
const server = http.createServer(routes);
server.listen(3000);

And updated file for routes.js is shown below −

const fs = require('fs');
const requestHandler=(req, res)=>{
   const url = req.url;
   if(url === '/'){
      res.write('<html>');
      res.write('<head> <title> Hello TutorialsPoint </title> </head>');
      res.write(' <body> <form action="/username" method="POST"> <input type="te
      xt" name="username"/> <button type="submit">Submit</button> </body>');
      res.write('</html>');
      return res.end();
   }
   if(url === '/username' && req.method === 'POST'){
      const requestBody = [];
      req.on('data', (chunks)=>{
         requestBody.push(chunks);
      });
      return req.on('end', ()=>{
         const parsedData = Buffer.concat(requestBody).toString();
         const username = parsedData.split('=')[1];
         fs.writeFile('username.txt', username, (error)=>{
            console.log(error);
         });
         //redirect
         res.statusCode=302;
         res.setHeader('Location','/');
         return res.end();
      });
   }
   res.write('<html>');
   res.write('<head> <title> Hello TutorialsPoint </title> </head>');
   res.write(' <body> Hello </body>');
   res.write('</html>');
   res.end();
}
module.exports= requestHandler;

Updated on: 13-May-2020

95 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements