【发布时间】:2021-02-24 08:36:58
【问题描述】:
我正在编写一个通过流向客户端发送视频文件的函数。它正常工作,除了在每个请求中它打开一个文件描述符但从不关闭它。这意味着这些文件以后无法删除,因为它们被 Node 进程阻止。
这是导致这种情况的函数:
exports.stream = (req, res, next) => {
const range = req.headers.range;
const volumeName = req.query.volume;
const folderPath = req.query.folder;
const fileName = req.query.file;
if (!range) return res.sendStatus(416);
try {
let volume = Services.volumes.get.byName(volumeName);
let path = volume.location + folderPath + fileName;
let pathExists = Services.files.get.exists(path);
if (!pathExists) return res.status(404).send('unable to stream file, path not exists');
let stats = fs.statSync(path);
if (!stats.isFile()) {
return res.status(400).send('requested path is not a file: ' + path);
}
const fileSize = stats.size;
const parts = range.replace(/bytes=/, "").split("-");
const start = parseInt(parts[0], 10);
let end = parts[1] ? parseInt(parts[1], 10) : fileSize - 1;
let chunksize = (end - start) + 1;
const maxChunk = 1024 * 1024;
if (chunksize > maxChunk) {
end = start + maxChunk - 1;
chunksize = (end - start) + 1;
}
res.writeHead(206, {
'Content-Range': `bytes ${start}-${end}/${fileSize}`,
'Accept-Ranges': 'bytes',
'Content-Length': chunksize,
'Content-Type': 'video/mp4',
});
let stream = fs.createReadStream(path, {start: start, end: end, autoClose: true});
stream.on('open', function () {
stream.pipe(res);
});
stream.on('error', function (err) {
res.end(err);
});
stream.on('close', function () {
stream.destroy();
});
} catch (e) {
next(new Error('unable to stream path: ' + e));
}
};
【问题讨论】:
标签: javascript node.js file video-streaming file-descriptor