DEV Community

DevFrontier
DevFrontier

Posted on

Node.js: Practical Coding Challenges

Create a Simple HTTP Server
Challenge: Create a server that returns "Hello World" when visiting /, and returns "Not Found" with a 404 status for other routes.

Solution:

const http = require('http');

const server = http.createServer((req, res) => {
  if (req.url === '/' && req.method === 'GET') {
    res.writeHead(200, { 'Content-Type': 'text/plain' });
    res.end('Hello World');
  } else {
    res.writeHead(404, { 'Content-Type': 'text/plain' });
    res.end('Not Found');
  }
});

server.listen(3000, () => console.log('Server running on port 3000'));
Enter fullscreen mode Exit fullscreen mode

Key Points:

  • Basic http module usage.
  • Correct status codes & headers.
  • Route/method checking.

Read and Write a File
Challenge: Read a data.txt file, append " - Updated" to its contents, and save to output.txt.

Solution:

const fs = require('fs');

fs.readFile('data.txt', 'utf8', (err, data) => {
  if (err) throw err;
  const updatedData = data + ' - Updated';
  fs.writeFile('output.txt', updatedData, (err) => {
    if (err) throw err;
    console.log('File written successfully');
  });
});
Enter fullscreen mode Exit fullscreen mode

Key Points:

  • Use asynchronous file I/O.
  • Proper error handling.

Handle POST Request Data
Challenge: Create a server that accepts JSON data via POST and responds with { received: true, data: ... }.

Solution:

const http = require('http');

const server = http.createServer((req, res) => {
  if (req.method === 'POST') {
    let body = '';
    req.on('data', chunk => (body += chunk));
    req.on('end', () => {
      try {
        const data = JSON.parse(body);
        res.writeHead(200, { 'Content-Type': 'application/json' });
        res.end(JSON.stringify({ received: true, data }));
      } catch (err) {
        res.writeHead(400, { 'Content-Type': 'application/json' });
        res.end(JSON.stringify({ error: 'Invalid JSON' }));
      }
    });
  } else {
    res.writeHead(405, { 'Content-Type': 'application/json' });
    res.end(JSON.stringify({ error: 'Method Not Allowed' }));
  }
});

server.listen(3000, () => console.log('Server running on port 3000'));
Enter fullscreen mode Exit fullscreen mode

Key Points:

  • Manual body parsing without libraries.
  • JSON validation with try/catch.
  • Proper HTTP status codes.

Use Streams for Large File Copy

  • Challenge: Copy large.txt to copy.txt using streams.

Solution:

const fs = require('fs');

const readStream = fs.createReadStream('large.txt');
const writeStream = fs.createWriteStream('copy.txt');

readStream.pipe(writeStream);

writeStream.on('finish', () => {
  console.log('File copied successfully');
});
Enter fullscreen mode Exit fullscreen mode

Key Points:

  • Use .pipe() for efficient data transfer.
  • Handle big files without loading them fully into memory.

Promise-based File Reading
Challenge: Create a function readFileAsync that returns a promise with file content.

Solution:

const fs = require('fs');

function readFileAsync(path) {
  return new Promise((resolve, reject) => {
    fs.readFile(path, 'utf8', (err, data) => {
      if (err) reject(err);
      else resolve(data);
    });
  });
}

readFileAsync('data.txt')
  .then(content => console.log(content))
  .catch(err => console.error(err));
Enter fullscreen mode Exit fullscreen mode

Key Points:

  • Promise wrapper for callback-based APIs.
  • Proper resolve/reject handling.

Async/Await API Call
Challenge: Fetch data from an API and log the title of the first item.

Solution:

const https = require('https');

async function fetchData() {
  return new Promise((resolve, reject) => {
    https.get('https://jsonplaceholder.typicode.com/posts', res => {
      let data = '';
      res.on('data', chunk => (data += chunk));
      res.on('end', () => resolve(JSON.parse(data)));
    }).on('error', reject);
  });
}

(async () => {
  try {
    const posts = await fetchData();
    console.log(posts[0].title);
  } catch (err) {
    console.error('Error fetching data:', err);
  }
})();
Enter fullscreen mode Exit fullscreen mode

Key Points:

  • Async/Await with Promises.
  • Native https request handling.

Simple Express API
Challenge: Build a small Express server with /hello route returning JSON { message: "Hello" }.

Solution:

const express = require('express');
const app = express();

app.get('/hello', (req, res) => {
  res.json({ message: 'Hello' });
});

app.listen(3000, () => console.log('Server running on port 3000'));
Enter fullscreen mode Exit fullscreen mode

Key Points:

  • Express routing basics.
  • Returning JSON.

Top comments (0)