繁体   English   中英

如何处理对node.js服务器中的文件的多个请求

[英]How to handle multiple requests to a file in node.js server

我正在尝试在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');
})

您正在使用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)
    })
})

您已经在使用快递,无需重新发明轮子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
    });
})

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM