Static File Server
NodeJS
Hard
3 views
Problem Description
Serve a local file for /file and 404 otherwise.
Output Format
Start server code.
Constraints
Use fs.createReadStream.
Official Solution
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'));
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!