我尝试在node.js服务器中提供多个音频文件,但是当多个客户端尝试访问时,服务器有时会失败。我该如何解决这个问题?
express = require('express');
const http = require('http');
const path = require('path');
const fs = require('fs');
const app = express();
app.get('/', function (request, response) {
let fpath = base_dir + filenames[getIndex(filenames.length)];
let filestream = fs.createReadStream(fpath);
var d = new Date();
filestream.on('open', function() {
let stats = fs.statSync(fpath);
let fileSizeInBytes = stats["size"];
response.writeHead(200, {
"Accept-Ranges": "bytes",
'Content-Type': 'audio/mpeg',
'Content-Length': fileSizeInBytes});
filestream.pipe(response);
});
})
app.listen(3000, function () {
console.log('Audio file provider listening on port 3000');
})
答案 0 :(得分:3)
您正在使用fs.statSync()
,它将阻止该线程同时侦听传入连接。相反,您应该切换到异步版本fs.stat()
。
app.get('/', (req, res) => {
let fpath = base_dir + filenames[getIndex(filenames.length)]
let d = new Date()
fs.stat(fpath, (err, stats) => {
// Handle Error when trying to get file stats
// Respond with 500 Internal Server Error
if (err) {
console.log(err)
return res.sendStatus(500)
}
let {size} = stats
res.status(200)
res.setHeader('Accept-Ranges', 'bytes')
res.setHeader('Content-Type', 'audio/mpeg')
res.setHeader('Content-Length', size)
fs.createReadStream(fpath).pipe(res)
})
})
答案 1 :(得分:0)
您已经使用快递,无需重新发明轮子http://expressjs.com/en/4x/api.html#res.sendFile
app.get('/', function (request, response) {
let fpath = base_dir + filenames[getIndex(filenames.length)];
response.sendFile(fpath, function(err) {
//Handle err if any
});
})