Creating a Simple http server in node.js to serve pdf


Overview

Creating a simple http server listening at port 3000 and is used to serve pdf.

Code


													
//serve-pdf.js
var http = require('http');
var fs = require('fs');
console.log('Server will listen at :  127.0.0.1:3000 ');
http.createServer( (req, res)=> {
	console.log("Port Number : 3000");
	// Change the MIME type to application/pdf
	res.writeHead(200, {"Content-Type": "application/pdf"});
	 
	fs.readFile('index.pdf', (error,data) => {
		if(error){
			res.json({'status':'error',msg:err});
		}else{			
			res.write(data);
			res.end();       
		}
	});
}).listen(3000);
													
												

Run

  • Now run the snippet using the following command :
    													
    >node serve-pdf.js