使用 Express.js 構(gòu)建一個簡單的 Node.js 應(yīng)用程序來下載 PDF
介紹
在本教程中,我們將逐步介紹使用 Express.js 構(gòu)建 Node.js 應(yīng)用程序的過程,該應(yīng)用程序允許用戶下載 PDF 文件。對于從文檔管理系統(tǒng)到教育平臺的各種應(yīng)用程序來說,這都是一個有用的功能。
前提
在我們開始之前,請確保您具備以下先決條件:
安裝 Node.js(https://nodejs.org/)
安裝 Npm (https://www.npmjs.com/)
設(shè)置項目目錄并使用 初始化 Node.js 項目npm init。
第 1 步:項目設(shè)置
為您的項目創(chuàng)建一個新目錄 (app.js),并使用以下命令初始化 Node.js 項目:
npm init
第2步:安裝依賴項
為您的項目安裝必要的依賴項。您可以通過運行以下命令來執(zhí)行此操作:
npm i express
第 3 步:設(shè)置 Express 應(yīng)用程序
創(chuàng)建 Express 應(yīng)用程序并設(shè)置基本 Express 服務(wù)器。這是此步驟的代碼:
const express = require('express'); const app = express(); const port = 3000; const fs = require('fs');
步驟 4:創(chuàng)建 PDF 下載路徑
創(chuàng)建處理 PDF 文件下載的 Express 路由。這是代碼:
app.get('/download-pdf', (req, res) => { const filePath = `./pdfs/java.pdf`; });
確保您創(chuàng)建了一個名為“pdfs添加您自己的 pdf 文件”的文件夾,我的文件名為java.pdf
步驟5:檢查PDF文件是否存在
使用該fs.existsSync方法檢查指定目錄中是否存在PDF文件。如果文件不存在,我們將處理文件未找到錯誤。
if (!fs.existsSync(filePath)) { const notFoundError = new CustomError(404, 'PDF file not found'); return next(notFoundError); }
第 6 步:發(fā)送 PDF 文件以供下載
如果文件存在,我們可以使用res.download發(fā)送PDF文件的方法進行下載。這是此步驟的代碼:
res.download(filePath, `java.pdf`, (err) => { if (err) { const downloadError = new CustomError(500, 'Error: Unable to download the PDF file'); return next(downloadError); } }); });
第7步:錯誤處理
實施錯誤處理以捕獲并響應(yīng)各種錯誤,例如找不到文件或下載錯誤。以下是處理 Express 應(yīng)用中的錯誤的方法:
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' }); } });
第 8 步:運行應(yīng)用程序
使用以下代碼啟動 Node.js 應(yīng)用程序:
app.listen(port, () => { console.log(`App listening on port ${port}`); });
現(xiàn)在你應(yīng)該擁有這個——
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}`); });
現(xiàn)在您測試或運行您的應(yīng)用程序node app.js,然后使用您選擇的任何瀏覽器 {Chrome} 訪問此路由http://localhost:3000/download-pdf
就這樣??????文章來源:http://www.zghlxwxcb.cn/article/384.html
文章來源地址http://www.zghlxwxcb.cn/article/384.html
到此這篇關(guān)于使用 Express.js 構(gòu)建一個簡單的 Node.js 應(yīng)用程序來下載 PDF的文章就介紹到這了,更多相關(guān)內(nèi)容可以在右上角搜索或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!