我正在尝试在express
应用中了解以下两条路线之间的区别。
const express = require('express')
const app = express()
const LOG_FOLDER = '/my/log/folder'
app.get('/log_stream/:id', (req, res, next) => {
if (req.fresh) {
res.sendStatus(304)
}
let logFile = path.resolve(LOG_FOLDER, req.params.id + '.log')
let readStream = fs.createReadStream(logFile)
readStream.on('open', () => {
readStream.pipe(res)
})
readStream.on('error', (err) => {
res.status(500).json({ 'error': err })
})
})
app.get('/log/:id', (req, res, next) => {
if (req.fresh) {
res.sendStatus(304)
}
let opts = {
dotfiles: 'deny'
}
let logFile = path.resolve(LOG_FOLDER, req.params.id + '.log')
let readStream = fs.createReadStream(logFile)
readStream.on('open', () => {
res.sendFile(logFile, opts, (err) => {
if (err) {
next(err)
}
})
})
readStream.on('error', (err) => {
res.status(500).json({ 'error': err })
})
})
app.listen(3000)
有没有首选的方法?
主要区别似乎在于标题,因为res.sendFile()
函数会自动设置其中的许多标题。