Building a Simple Node.js App for Downloading PDFs using Express.js
Introduction
In this tutorial, we'll walk through the process of building a Node.js application using Express.js that allows users to download PDF files. This can be a useful feature for a variety of applications, from document management systems to educational platforms.
Prerequisites
Before we get started, ensure you have the following prerequisites in place:
- Node.js and npm installed.
- Set up a project directory and initialize a Node.js project using
npm init
.
Step 1: Project Setup
Create a new directory (app.js) for your project and initialize a Node.js project using the following command:
npm init
Step 2: Install Dependencies
Install the necessary dependencies for your project. You can do this by running the following command:
npm i express
Step 3: Setting Up the Express App
Create an Express application and set up a basic Express server. Here's the code for this step:
const express = require('express');
const app = express();
const port = 3000;
const fs = require('fs');
Step 4: Creating a Route for PDF Download
Create an Express route that handles PDF file downloads. Here's the code:
app.get('/download-pdf', (req, res) => {
const filePath = `./pdfs/java.pdf`;
});
Make sure you create a folder called pdfs
add your own pdf file to it mine is called java.pdf
Step 5: Check if the PDF File Exists
Use the fs.existsSync
method to check if the PDF file exists in the specified directory. If the file doesn't exist, we will handle the file not found error.
if (!fs.existsSync(filePath)) {
const notFoundError = new CustomError(404, 'PDF file not found');
return next(notFoundError);
}
Step 6: Send the PDF File for Download
If the file exists, we can use the res.download
method to send the PDF file for download. Here's the code for this step:
res.download(filePath, `java.pdf`, (err) => {
if (err) {
const downloadError = new CustomError(500, 'Error: Unable to download the PDF file');
return next(downloadError);
}
});
});
Step 7: Error Handling
Implement error handling to catch and respond to various errors, such as file not found or download errors. Here's how you can handle errors in your Express app:
app.use((err, req, res, next) => {
if (err instanceof customError) {
res.status(err.statusCode).json({ error: err.message });
} else {
// Handle other errors
res.status(500).json({ error: 'Internal Server Error' });
}
});
Step 8: Run the Application
Start your Node.js application with the following code:
app.listen(port, () => {
console.log(`App listening on port ${port}`);
});
Now you should have this --
const express = require('express');
const app = express();
const port = 3000;
const fs = require('fs');
// Replace this with your actual PDF directory path
const pdfDirectory = './pdfs';
// Error handling class
class CustomError extends Error {
constructor(statusCode, message) {
super();
this.statusCode = statusCode;
this.message = message;
}
}
// Middleware for error handling
app.use((err, req, res, next) => {
if (err instanceof CustomError) {
res.status(err.statusCode).json({ error: err.message });
} else {
res.status(500).json({ error: 'Internal Server Error' });
}
});
app.get('/download-pdf', (req, res) => {
const filePath = `${pdfDirectory}/java.pdf`;
if (!fs.existsSync(filePath)) {
const notFoundError = new CustomError(404, 'PDF file not found');
return next(notFoundError);
}
res.download(filePath, `java.pdf`, (err) => {
if (err) {
const downloadError = new CustomError(500, 'Error: Unable to download the PDF file');
return next(downloadError);
}
});
});
app.listen(port, () => {
console.log(`App listening on port ${port}`);
});
Now you test or run your app node app.js
you then use any browser {Chrome} of your choice to access this route http://localhost:3000/download-pdf
And That's It πππ
Top comments (0)