NodeJs/Express 在浏览器中显示pdf文件
NodeJs/Express display pdf file in browser
我正在处理 NodeJs/Express 项目,需要在存储在
中的 browesr pdf 文件中显示
/public/images
这里是相关的路由器代码:
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)
}
})
我没有收到任何错误,但没有任何反应 ie.browser 没有打开等等。
在此先感谢您的指导。
我要做的第一个更改是删除 async
。它只会用不需要的 Promises 弄乱代码。
其次,我不再需要捕获异常,使用 fs.existsSync(path)
验证文件是否存在。尽量不要经常引发异常。如果您知道某些东西会引发异常,请对其进行测试。
最后,也是最重要的,我创建了文件的读取流,并将结果通过管道传输到 fs.createReadStream(path).pipe(res)
的响应。这样,客户端在读取文件时会收到文件,并且您的内存是空闲的。非常适合大文件。
读取文件可能会占用大量内存,因此将其全部加载到内存中是一种不好的做法。您只需要少量请求即可使您的机器过载。
您可以阅读有关管道方法的更多信息 here。
在此示例中,对 /router/show_file
的任何 GET 调用都将 return 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'))
我正在处理 NodeJs/Express 项目,需要在存储在
中的 browesr pdf 文件中显示/public/images
这里是相关的路由器代码:
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)
}
})
我没有收到任何错误,但没有任何反应 ie.browser 没有打开等等。 在此先感谢您的指导。
我要做的第一个更改是删除 async
。它只会用不需要的 Promises 弄乱代码。
其次,我不再需要捕获异常,使用 fs.existsSync(path)
验证文件是否存在。尽量不要经常引发异常。如果您知道某些东西会引发异常,请对其进行测试。
最后,也是最重要的,我创建了文件的读取流,并将结果通过管道传输到 fs.createReadStream(path).pipe(res)
的响应。这样,客户端在读取文件时会收到文件,并且您的内存是空闲的。非常适合大文件。
读取文件可能会占用大量内存,因此将其全部加载到内存中是一种不好的做法。您只需要少量请求即可使您的机器过载。
您可以阅读有关管道方法的更多信息 here。
在此示例中,对 /router/show_file
的任何 GET 调用都将 return 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'))