NodeJs/Express 在浏览器中显示pdf文件

gor*_*yef 2 browser pdf readfile node.js express

我正在开发 NodeJs/Express 项目,需要在浏览器中显示 pdf 文件,该文件存储在

/公共/图像

这是相关的路由器代码:

router.post('/show_file', async (req,res)=>{
  try {
     let path = './public/images/1.pdf'
     var data =fs.readFileSync(path);
     res.contentType("application/pdf");
     res.send(data);
   } catch (err) {
     res.status(500)
     console.log(err)
     res.send(err.message)
   }
})
Run Code Online (Sandbox Code Playgroud)

我没有收到任何错误,但没有发生任何事情,即浏览器未打开等。提前感谢您的任何指导。

Thi*_*nho 7

我要做的第一个更改是删除async. 它只会用不需要的 Promise 搞乱代码。

其次,我不再需要捕获异常,而是使用fs.existsSync(path). 尽量不要经常出现异常。如果您知道某些东西可能会引发异常,请对其进行测试。

最后也是最重要的,我创建了文件的读取流,并将结果通过管道传输到响应fs.createReadStream(path).pipe(res)。这样,客户端会在读取文件时收到该文件,并且可以节省内存。非常适合大文件。

读取文件可能会占用大量内存,因此将其全部加载到内存中是一种不好的做法。您只需要少量请求即可使您的机器超载。

您可以在此处阅读有关管道方法的更多信息。

在此示例中,任何 GET 调用都/router/show_file将返回 pdf。

const express = require('express')
const app = express()
const fs = require('fs')
const router = express.Router()

router.get('/show_file', (req, res) => {
    const path = './public/images/1.pdf'
    if (fs.existsSync(path)) {
        res.contentType("application/pdf");
        fs.createReadStream(path).pipe(res)
    } else {
        res.status(500)
        console.log('File not found')
        res.send('File not found')
    }
})

app.use('/router', router) // Here we pass the router to the app with a path

app.listen(9999, () => console.log('Listening to port 9999'))
Run Code Online (Sandbox Code Playgroud)