node js serve pdf file

  1. First, import the required modules by using the require() function. For instance, you can import the 'http' and 'fs' modules for handling HTTP requests and file system operations.

  2. Create an HTTP server using the createServer() method from the 'http' module. Within the createServer() method, use a callback function with request and response parameters to handle incoming requests.

  3. Read the PDF file using the fs.readFile() method to load the PDF file from the file system. Provide the file path and a callback function to handle any errors and the file data.

  4. Set the appropriate Content-Type header in the response object to 'application/pdf' to indicate that the server will be sending a PDF file.

  5. Send the PDF file data in the response using the response.write() method, and end the response with response.end() to complete the response.

  6. Finally, listen on a specific port for incoming requests using the server.listen() method to start the server and make the PDF file accessible through the specified port.