Articles on Trending Technologies

Technical articles with clear explanations and examples

How to use express router

Shyam Hande
Shyam Hande
Updated on 13-May-2020 2K+ Views

In earlier examples, we wrote all routing code in a single file App.js. But in real world scenarios, we have to split the code into multiple files.We can create separate files and import them but express gives a router mechanism which is easy to use.Create a separate file called route.js (name can be anything)Create router using express −const express = require('express'); const router = express.Router();exporting router −module.exports = router;Adding routing functions −router.get('/add-username', (req, res, next)=>{    res.send(' Send '); });  router.post('/post-username', (req, res, next)=>{    console.log('data: ', req.body.username);    res.redirect('/'); });Similar to functions we used in App.js ...

Read More

Parsing incoming requests in express.js

Shyam Hande
Shyam Hande
Updated on 13-May-2020 1K+ Views

To receive some data in http request , lets add a form on url path ‘/add-username’:app.use('/add-username', (req, res, next)=>{    res.send(' Send '); });For parsing the http request, we requires a third party library body-parser: It’s a production required dependencynpm install –save body-parserexpress js provides middleware use function to include a body parser before adding middleware.const http = require('http'); const express = require('express'); const bodyParser = require('body-parser'); const app = express(); app.use(bodyParser.urlencoded({extended: false}));the use(0 function shown above uses next() function by default so http request gets passed to next middleware without any trouble.The above ...

Read More

Handling different routes in express.js

Shyam Hande
Shyam Hande
Updated on 13-May-2020 651 Views

For handling different routes, use() function is used. use() function has multiple overloaded version, one of version also takes url path as a argument. Based on the url path, the requests will be filtered out for respective middleware.const http = require('http'); const express = require('express'); const app = express(); app.use('/', (req, res, next)=>{    console.log('first middleware');    res.send(' first midleware:    Hello Tutorials Point '); }); const server = http.createServer(app); server.listen(3000);in above example we used ‘/’ as url path, it’s a default.Now, as every route starts with ‘/’, the above middleware executes for every http request. It works for ‘/’ ...

Read More

Understanding the different error types and handling in Node.js

Shyam Hande
Shyam Hande
Updated on 13-May-2020 567 Views

Error types are −Syntax errorRuntime errorLogical errorSyntax error −These are easy to find as most of the development tools like visual code studio shows red lines whenever there is a syntax error. The suggestion for resolution may be not be correct in tools but it gives an idea of what went wrong in a specific area of code.On running an app, console terminal will shows the errors. Console log can point to exact line where error occurred.More common syntax error are like missing closing bracket for a block , it will need to identify correct blocks .Runtime error −Example − ...

Read More

How to install third party packages using npm

Shyam Hande
Shyam Hande
Updated on 13-May-2020 856 Views

Now, so far we saw how to create a node project with npm init command and also adding scripts to run application.Why third party libraries are requiredWe used core modules of node.js like http, fs etc which are available by default with node.js but working only with these core modules does not simplify our work. To add more useful functionality and simpler code we requires to install third party libraries like express, body-parser etc.We get the third party libraries from cloud stored npm repository. Installation is done using npm install command.NodemonWe are running our App.js file using npm start command. ...

Read More

Understanding the npm - Node module system

Shyam Hande
Shyam Hande
Updated on 13-May-2020 221 Views

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.jsWe 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('');       res.write(' Hello TutorialsPoint ');       res.write('       Submit ');       res.write('');     ...

Read More

How Node.js works in background - A brief analysis

Shyam Hande
Shyam Hande
Updated on 13-May-2020 428 Views

Node.js uses only one JavaScript execution thread.Question is − how Node.js process multiple http or any other requests and there can be question on performance, security as well?Node.js starts event loop on application start and handles callback functions using it.Node.js maintains a worker pool. Long running operations are transferred to this worker pool and event pool only handles responses from this worker pool on completion of tasks.Worker pool works with operating system to do the heavy lifting of work and managing scheduling of tasks.Worker pool once finished task responds to event loop using callback functions.Event loop maintains the order of ...

Read More

Understanding blocking and unblocking of code execution in Node

Shyam Hande
Shyam Hande
Updated on 13-May-2020 624 Views

Now, we have a file writing function writeFileSync in fs module as shown below −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.writeFileSync('username.txt', username);    //redirect res.statusCode=302;    res.setHeader('Location', '/');    return res.end(); });Sync means synchronized. It’s a blocking code example. Once file write is completed then only code execution for rest of the file starts. Above code is simpler but if we have a large file handling operation it will result into slow performance of app.This way of code execution will slow down the ...

Read More

Understanding the Event driven code execution approach in Node

Shyam Hande
Shyam Hande
Updated on 13-May-2020 212 Views

In earlier example in App.js , we saw how to parse data from request using data and end event.Code snippet below shows the if block for that −if(url === '/username' && req.method === 'POST'){    const requestBody = [];    req.on('data', (chunks)=>{       requestBody.push(chunks);    });    req.on('end', ()=>{       const parsedData = Buffer.concat(requestBody).toString();       const username = parsedData.split('=')[1];       fs.writeFileSync('username.txt', username);    });    //redirect    res.statusCode=302;    res.setHeader('Location', '/');    return res.end(); }In above code block, we have two events (data and end) registered if path matches to ‘/username’ and ...

Read More

Parsing request Body in Node

Shyam Hande
Shyam Hande
Updated on 13-May-2020 3K+ Views

Earlier in simple code example, we saw how to route a request and creating a file to input the test data.Now, we want to save the user entered input data into text file.How Node.js handles incoming request dataNode.js reads data in chunks means it uses streams to read data . Once node completes reading request data, we can proceed to use it for our purpose.First read data in chunks const requestBody = []; req.on(‘data’, (chunks)=>{    requestBody.push(chunks); });We have registred an event called ‘data’ on incoming http request. This event will keep on streaming data and pushes to requestBody const ...

Read More
Showing 54231–54240 of 61,297 articles
Advertisements