nodejs http file server serving file for download
Objective: Create a node js http server accepting incoming request and respond with a file for download. If the request querys for a specific file, respond with that file instead.
Solution: Include http, url and fs module. http for creating the http server, url for getting query parameter from the url, and fs for reading the file into a stream.The key is to set the response header to a 'Content-disposition', 'attachment; filename=theDocument.txt'
var http = require('http'), url = require('url'), fs = require('fs'); //create the http server listening on port 3333 http.createServer(function (req, res) { var query = url.parse(req.url, true).query; if (typeof query.file === 'undefined') { //specify Content will be an attachment res.setHeader('Content-disposition', 'attachment; filename=theDocument.txt'); res.setHeader('Content-type', 'text/plain'); res.end("Hello, here is a file for you!"); } else { //read the image using fs and send the image content back in the response fs.readFile('/path/to/a/file/directory/' + query.file, function (err, content) { if (err) { res.writeHead(400, {'Content-type':'text/html'}) console.log(err); res.end("No such file"); } else { //specify Content will be an attachment res.setHeader('Content-disposition', 'attachment; filename='+query.file); res.end(content); } }); } }).listen(3333); console.log("Server running at http://localhost:3333/");
Download the file from the server on a browser.
http://localhost:3333/
http://localhost:3333/?file=afile.txt
Search within Codexpedia
Custom Search
Search the entire web
Custom Search
Related Posts