{"id":136417,"date":"2024-07-25T19:04:04","date_gmt":"2024-07-25T19:04:04","guid":{"rendered":"https:\/\/www.sushilkumar.ind.in\/blog\/?p=136417"},"modified":"2024-08-06T17:45:26","modified_gmt":"2024-08-06T17:45:26","slug":"some-coding-interview-question-answer-of-nodejs-and-express-js","status":"publish","type":"post","link":"https:\/\/www.sushilkumar.ind.in\/blog\/node-js\/some-coding-interview-question-answer-of-nodejs-and-express-js\/","title":{"rendered":"Coding interview questions related to Node.js and Express.js, along with their answers"},"content":{"rendered":"\n<h3 class=\"wp-block-heading\">1. <strong>What is the purpose of <strong>app.use()<\/strong> in Express.js?<\/strong><\/h3>\n\n\n\n<p><strong>Answer:<\/strong><\/p>\n\n\n\n<p>In Express.js, <strong>app.use()<\/strong> is a method used to add middleware to your application. Middleware functions are functions that have access to the request object (<strong>req<\/strong>), the response object (<strong>res<\/strong>), and the <strong>next<\/strong> middleware function in the application\u2019s request-response cycle. They can modify the request and response objects, end the request-response cycle, or call the <strong>next<\/strong> middleware function in the stack.<\/p>\n\n\n\n<p>Example:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>const express = require('express');\nconst app = express();\n\n\/\/ Middleware to log request details\napp.use((req, res, next) =&gt; {\n    console.log(`${req.method} ${req.url}`);\n    next(); \/\/ Pass control to the next middleware\n});<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">2. <strong>How can you handle errors in an Express.js application?<\/strong><\/h3>\n\n\n\n<p><strong>Answer:<\/strong><\/p>\n\n\n\n<p>In Express.js, you handle errors by defining an error-handling middleware. Error-handling middleware functions have four arguments: <strong>err<\/strong>, <strong>req<\/strong>, <strong>res<\/strong>, and <strong>next<\/strong>. They are defined after all other middleware and routes.<\/p>\n\n\n\n<p>Example:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>const express = require('express');\nconst app = express();\n\n\/\/ Some route that may cause an error\napp.get('\/error', (req, res, next) =&gt; {\n    try {\n        throw new Error('Something went wrong!');\n    } catch (err) {\n        next(err); \/\/ Pass errors to the error-handling middleware\n    }\n});\n\n\/\/ Error-handling middleware\napp.use((err, req, res, next) =&gt; {\n    console.error(err.stack);\n    res.status(500).send('Something broke!');\n});\n\napp.listen(3000, () =&gt; {\n    console.log('Server running on port 3000');\n});<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">3. <strong>How do you set up a basic route in Express.js?<\/strong><\/h3>\n\n\n\n<p><strong>Answer:<\/strong><\/p>\n\n\n\n<p>To set up a basic route in Express.js, use the <strong>app.get()<\/strong>, <strong>app.post()<\/strong>, <strong>app.put()<\/strong>, or <strong>app.delete()<\/strong> methods, depending on the HTTP method you want to handle. Each of these methods takes a route path and a callback function to handle requests to that path.<\/p>\n\n\n\n<p>Example:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>const express = require('express');\nconst app = express();\n\n\/\/ Handle GET request to the root URL\napp.get('\/', (req, res) =&gt; {\n    res.send('Hello, world!');\n});\n\n\/\/ Handle POST request to \/submit\napp.post('\/submit', (req, res) =&gt; {\n    res.send('Form submitted!');\n});\n\napp.listen(3000, () =&gt; {\n    console.log('Server running on port 3000');\n});<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">4. <strong>How do you parse JSON bodies in Express.js?<\/strong><\/h3>\n\n\n\n<p><strong>Answer:<\/strong><\/p>\n\n\n\n<p>To parse JSON bodies in Express.js, you use the <strong>express.json()<\/strong> middleware. This middleware parses incoming requests with JSON payloads and makes the parsed data available in <strong>req.body<\/strong>.<\/p>\n\n\n\n<p>Example:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>const express = require('express');\nconst app = express();\n\n\/\/ Middleware to parse JSON bodies\napp.use(express.json());\n\napp.post('\/data', (req, res) =&gt; {\n    console.log(req.body); \/\/ Parsed JSON data\n    res.send('Data received');\n});\n\napp.listen(3000, () =&gt; {\n    console.log('Server running on port 3000');\n});<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">5. <strong>How do you serve static files in Express.js?<\/strong><\/h3>\n\n\n\n<p><strong>Answer:<\/strong><\/p>\n\n\n\n<p>To serve static files in Express.js, use the <strong>express.static()<\/strong> middleware. You specify a directory from which static files should be served.<\/p>\n\n\n\n<p>Example:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>const express = require('express');\nconst path = require('path');\nconst app = express();\n\n\/\/ Serve static files from the \"public\" directory\napp.use(express.static(path.join(__dirname, 'public')));\n\napp.listen(3000, () =&gt; {\n    console.log('Server running on port 3000');\n});<\/code><\/pre>\n\n\n\n<p>In this example, if you place files in the <strong>public<\/strong> directory, they can be accessed directly via the URL path.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">6. <strong>How can you handle different HTTP methods for the same route?<\/strong><\/h3>\n\n\n\n<p><strong>Answer:<\/strong><\/p>\n\n\n\n<p>You can handle different HTTP methods for the same route by using <strong>app.get()<\/strong>, <strong>app.post()<\/strong>, <strong>app.put()<\/strong>, <strong>app.delete()<\/strong>, etc., for the specific methods you want to handle.<\/p>\n\n\n\n<p>Example:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>const express = require('express');\nconst app = express();\n\n\/\/ Handle GET request\napp.get('\/resource', (req, res) =&gt; {\n    res.send('GET request to \/resource');\n});\n\n\/\/ Handle POST request\napp.post('\/resource', (req, res) =&gt; {\n    res.send('POST request to \/resource');\n});\n\n\/\/ Handle PUT request\napp.put('\/resource', (req, res) =&gt; {\n    res.send('PUT request to \/resource');\n});\n\n\/\/ Handle DELETE request\napp.delete('\/resource', (req, res) =&gt; {\n    res.send('DELETE request to \/resource');\n});\n\napp.listen(3000, () =&gt; {\n    console.log('Server running on port 3000');\n});<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">7. <strong>How do you perform asynchronous operations in Express.js?<\/strong><\/h3>\n\n\n\n<p><strong>Answer:<\/strong><\/p>\n\n\n\n<p>You can perform asynchronous operations in Express.js by using <strong>async<\/strong> functions and <strong>await<\/strong> syntax. This helps manage asynchronous code more cleanly compared to traditional callbacks or promises.<\/p>\n\n\n\n<p>Example:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>const express = require('express');\nconst app = express();\n\n\/\/ Example asynchronous operation\napp.get('\/data', async (req, res) =&gt; {\n    try {\n        const data = await someAsyncFunction(); \/\/ Assume this is an async function\n        res.json(data);\n    } catch (err) {\n        res.status(500).send('Server error');\n    }\n});\n\nasync function someAsyncFunction() {\n    \/\/ Simulate an async operation, e.g., fetching data from a database\n    return new Promise((resolve) =&gt; {\n        setTimeout(() =&gt; {\n            resolve({ message: 'Data fetched' });\n        }, 1000);\n    });\n}\n\napp.listen(3000, () =&gt; {\n    console.log('Server running on port 3000');\n});<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">8. <strong>How do you handle query parameters in Express.js?<\/strong><\/h3>\n\n\n\n<p><strong>Answer:<\/strong><\/p>\n\n\n\n<p>Query parameters in Express.js are accessed through <strong>req.query<\/strong>. Query parameters are typically included in the URL after a <strong>?<\/strong>, such as <strong>\/search?term=example<\/strong>.<\/p>\n\n\n\n<p>Example:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>const express = require('express');\nconst app = express();\n\napp.get('\/search', (req, res) =&gt; {\n    const term = req.query.term; \/\/ Access the 'term' query parameter\n    res.send(`Search term: ${term}`);\n});\n\napp.listen(3000, () =&gt; {\n    console.log('Server running on port 3000');\n});<\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\">9. Display Hostname and Platform Details<\/h4>\n\n\n\n<p><strong>File:<\/strong> <code>systemInfo.js<\/code><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>const os = require('os');\n\nconsole.log('Hostname:', os.hostname());\nconsole.log('Platform:', os.platform());\nconsole.log('Architecture:', os.arch());<\/code><\/pre>\n\n\n\n<p><strong>Run Command:<\/strong> <code>node systemInfo.js<\/code><\/p>\n\n\n\n<h4 class=\"wp-block-heading\">10. Display Text in Colors<\/h4>\n\n\n\n<p><strong>File:<\/strong> <code>coloredText.js<\/code><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>const colors = require('colors');\n\nconsole.log('This is red text'.red);\nconsole.log('This is green text'.green);\nconsole.log('This is blue text'.blue);\nconsole.log('This is yellow text'.yellow);<\/code><\/pre>\n\n\n\n<p><strong>Setup:<\/strong> <code>npm install colors<\/code><\/p>\n\n\n\n<p><strong>Run Command:<\/strong> <code>node coloredText.js<\/code><\/p>\n\n\n\n<h4 class=\"wp-block-heading\">11. User-defined Math Module<\/h4>\n\n\n\n<p><strong>File:<\/strong> <code>math.js<\/code> (module)<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\/\/ math.js\nmodule.exports = {\n    add: (a, b) =&gt; a + b,\n    subtract: (a, b) =&gt; a - b,\n    multiply: (a, b) =&gt; a * b,\n    divide: (a, b) =&gt; b !== 0 ? a \/ b : 'Cannot divide by zero'\n};<\/code><\/pre>\n\n\n\n<p><strong>File:<\/strong> <code>useMath.js<\/code> (usage)<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>const math = require('.\/math');\n\nconst a = 10;\nconst b = 5;\n\nconsole.log(`Addition: ${a} + ${b} = ${math.add(a, b)}`);\nconsole.log(`Subtraction: ${a} - ${b} = ${math.subtract(a, b)}`);\nconsole.log(`Multiplication: ${a} * ${b} = ${math.multiply(a, b)}`);\nconsole.log(`Division: ${a} \/ ${b} = ${math.divide(a, b)}`);<\/code><\/pre>\n\n\n\n<p><strong>Run Command:<\/strong> <code>node useMath.js<\/code><\/p>\n\n\n\n<h4 class=\"wp-block-heading\">12. Display Message with Delay<\/h4>\n\n\n\n<p><strong>File:<\/strong> <code>delayedMessage.js<\/code><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>const delay = (ms) =&gt; new Promise(resolve =&gt; setTimeout(resolve, ms));\n\nasync function showMessage() {\n    console.log('Message will appear after 3 seconds...');\n    await delay(3000);\n    console.log('Here is the delayed message!');\n}\n\nshowMessage();<\/code><\/pre>\n\n\n\n<p><strong>Run Command:<\/strong> <code>node delayedMessage.js<\/code><\/p>\n\n\n\n<h4 class=\"wp-block-heading\">12. Display Hostname and Platform Details via Express<\/h4>\n\n\n\n<p><strong>File:<\/strong> <code>server.js<\/code><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>const express = require('express');\nconst os = require('os');\n\nconst app = express();\nconst port = 3000;\n\napp.get('\/system-info', (req, res) =&gt; {\n    res.json({\n        hostname: os.hostname(),\n        platform: os.platform(),\n        architecture: os.arch()\n    });\n});\n\napp.listen(port, () =&gt; {\n    console.log(`Server listening at http:\/\/localhost:${port}`);\n});<\/code><\/pre>\n\n\n\n<p><strong>Run Command:<\/strong> <code>node server.js<\/code><\/p>\n\n\n\n<p><strong>Access:<\/strong> <code>http:\/\/localhost:3000\/system-info<\/code><\/p>\n\n\n\n<h4 class=\"wp-block-heading\">13. Display Text in Colors via Express<\/h4>\n\n\n\n<p><strong>File:<\/strong> <code>coloredTextServer.js<\/code><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>const express = require('express');\nconst colors = require('colors');\n\nconst app = express();\nconst port = 3001;\n\napp.get('\/colored-text', (req, res) =&gt; {\n    res.send(`\n        &lt;p style=\"color: red;\"&gt;This is red text&lt;\/p&gt;\n        &lt;p style=\"color: green;\"&gt;This is green text&lt;\/p&gt;\n        &lt;p style=\"color: blue;\"&gt;This is blue text&lt;\/p&gt;\n        &lt;p style=\"color: yellow;\"&gt;This is yellow text&lt;\/p&gt;\n    `);\n});\n\napp.listen(port, () =&gt; {\n    console.log(`Server listening at http:\/\/localhost:${port}`);\n});<\/code><\/pre>\n\n\n\n<p><strong>Run Command:<\/strong> <code>node coloredTextServer.js<\/code><\/p>\n\n\n\n<p><strong>Access:<\/strong> <code>http:\/\/localhost:3001\/colored-text<\/code><\/p>\n\n\n\n<h4 class=\"wp-block-heading\">14. Math Module and Use with Express<\/h4>\n\n\n\n<p><strong>File:<\/strong> <code>mathServer.js<\/code><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>const express = require('express');\nconst bodyParser = require('body-parser');\nconst math = require('.\/math');\n\nconst app = express();\nconst port = 3002;\n\napp.use(bodyParser.json());\n\napp.post('\/math', (req, res) =&gt; {\n    const { operation, a, b } = req.body;\n\n    if (typeof a !== 'number' || typeof b !== 'number') {\n        return res.status(400).json({ error: 'Invalid input' });\n    }\n\n    let result;\n\n    switch (operation) {\n        case 'add':\n            result = math.add(a, b);\n            break;\n        case 'subtract':\n            result = math.subtract(a, b);\n            break;\n        case 'multiply':\n            result = math.multiply(a, b);\n            break;\n        case 'divide':\n            result = math.divide(a, b);\n            break;\n        default:\n            return res.status(400).json({ error: 'Invalid operation' });\n    }\n\n    res.json({ result });\n});\n\napp.listen(port, () =&gt; {\n    console.log(`Server listening at http:\/\/localhost:${port}`);\n});<\/code><\/pre>\n\n\n\n<p><strong>Run Command:<\/strong> <code>node mathServer.js<\/code><\/p>\n\n\n\n<p><strong>Testing:<\/strong> Use Postman or <code>curl<\/code> for requests:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>curl -X POST http:\/\/localhost:3002\/math -H \"Content-Type: application\/json\" -d '{\"operation\":\"add\",\"a\":10,\"b\":5}'<\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\">15. Display Message with Delay via Express<\/h4>\n\n\n\n<p><strong>File:<\/strong> <code>delayedMessageServer.js<\/code><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>const express = require('express');\n\nconst app = express();\nconst port = 3003;\n\napp.get('\/delayed-message', (req, res) =&gt; {\n    setTimeout(() =&gt; {\n        res.send('Here is the delayed message!');\n    }, 3000);\n});\n\napp.listen(port, () =&gt; {\n    console.log(`Server listening at http:\/\/localhost:${port}`);\n});<\/code><\/pre>\n\n\n\n<p><strong>Run Command:<\/strong> <strong>node delayedMessageServer.js<\/strong><\/p>\n\n\n\n<p><strong>Access:<\/strong> <strong>http:\/\/localhost:3003\/delayed-message<\/strong><\/p>\n\n","protected":false},"excerpt":{"rendered":"<p>1. What is the purpose of app.use() in Express.js? Answer: In Express.js, app.use() is a method used to add middleware to your application. Middleware functions are functions that have access to the request object (req), the response object (res), and the next middleware function in the application\u2019s request-response cycle. They can modify the request and &hellip;<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":true,"template":"","format":"standard","meta":{"_acf_changed":false,"jetpack_post_was_ever_published":false,"_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":false,"_jetpack_newsletter_tier_id":0,"_jetpack_memberships_contains_paywalled_content":false,"_jetpack_memberships_contains_paid_content":false,"footnotes":"","jetpack_publicize_message":"","jetpack_publicize_feature_enabled":true,"jetpack_social_post_already_shared":true,"jetpack_social_options":{"image_generator_settings":{"template":"highway","enabled":false},"version":2}},"categories":[14180],"tags":[],"class_list":["post-136417","post","type-post","status-publish","format-standard","","category-node-js"],"jetpack_publicize_connections":[],"acf":[],"aioseo_notices":[],"jetpack_featured_media_url":"","jetpack_sharing_enabled":true,"jetpack_shortlink":"https:\/\/wp.me\/p99pkJ-zuh","_links":{"self":[{"href":"https:\/\/www.sushilkumar.ind.in\/blog\/wp-json\/wp\/v2\/posts\/136417"}],"collection":[{"href":"https:\/\/www.sushilkumar.ind.in\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.sushilkumar.ind.in\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.sushilkumar.ind.in\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.sushilkumar.ind.in\/blog\/wp-json\/wp\/v2\/comments?post=136417"}],"version-history":[{"count":8,"href":"https:\/\/www.sushilkumar.ind.in\/blog\/wp-json\/wp\/v2\/posts\/136417\/revisions"}],"predecessor-version":[{"id":136431,"href":"https:\/\/www.sushilkumar.ind.in\/blog\/wp-json\/wp\/v2\/posts\/136417\/revisions\/136431"}],"wp:attachment":[{"href":"https:\/\/www.sushilkumar.ind.in\/blog\/wp-json\/wp\/v2\/media?parent=136417"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.sushilkumar.ind.in\/blog\/wp-json\/wp\/v2\/categories?post=136417"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.sushilkumar.ind.in\/blog\/wp-json\/wp\/v2\/tags?post=136417"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}