Static File Server

Static File Server

Hard NodeJS HTTP & APIs 37 views
Explanation Complexity

Problem Statement

Serve a local file for /file and 404 otherwise.

Input Format

No input.

Output Format

Start server code.

Constraints

Use fs.createReadStream.

Input / Output Format

Input Format
No input.
Output Format
Start server code.
Constraints
Use fs.createReadStream.

Example Solution (Public)

NodeJS
const http = require('http');
const fs = require('fs');

const server = http.createServer((req, res) => {
  if (req.url !== '/file') {
    res.writeHead(404, { 'Content-Type': 'text/plain' });
    return res.end('Not found');
  }

  const stream = fs.createReadStream('meetcode.txt');
  stream.on('error', () => {
    res.writeHead(404, { 'Content-Type': 'text/plain' });
    res.end('Missing file');
  });
  res.writeHead(200, { 'Content-Type': 'text/plain' });
  stream.pipe(res);
});

server.listen(3005, () => console.log('http://localhost:3005'));

Official Solution Code

const http = require('http');
const fs = require('fs');

const server = http.createServer((req, res) => {
  if (req.url !== '/file') {
    res.writeHead(404, { 'Content-Type': 'text/plain' });
    return res.end('Not found');
  }

  const stream = fs.createReadStream('meetcode.txt');
  stream.on('error', () => {
    res.writeHead(404, { 'Content-Type': 'text/plain' });
    res.end('Missing file');
  });
  res.writeHead(200, { 'Content-Type': 'text/plain' });
  stream.pipe(res);
});

server.listen(3005, () => console.log('http://localhost:3005'));
Please login to submit solutions.
Editor
Output

                                        
Please login to submit solutions.