节点如何将文件传递到http.write方法

Node how to pass file to http.write method?

本文关键字:http write 方法 文件 节点      更新时间:2023-09-26

我想将文件打印到res.write()方法,但我得到错误:

TypeError: First argument must be a string or Buffer

我的代码:

var fs = require("fs");
var http = require("http");

http.createServer(function (req, res){
    res.write(getData());
    res.end();
}).listen(3333);

function getData(){
    fs.readFile('testfs.txt', function(err, data){
        if(err)
        {
            console.log("Error: " + err);
        }else {
            console.log(data.toString());
            return data.toString();
        }
    });
}

怎么了?

res.write既没有得到字符串也没有得到缓冲区,因为函数getData不是异步的。以下是我希望能解决您问题的解决方案:

http.createServer(function (req, res){
    getData(function(data){
        res.write(data);
        res.end();
    }));
}).listen(3333);
function getData(cb){
    fs.readFile('testfs.txt', function(err, data){
        if(err)
        {
            console.log("Error: " + err);
        }else {
            cb(data.toString());
        }
    });
}

其中cb参数显然是一个回调函数。

或者,您可以使用流:

const http = require('http');
const fs   = require('fs');
http.createServer((req, res) => {
  fs.createReadStream('testfs.txt')
    .on('error', (e) => {
      console.log('Error:', e);
      res.statusCode = 500;
      res.end();
    })
    .pipe(res)

}).listen(3333);

反过来做;只需调用getData并传入响应,然后在加载文件时,调用response.end(string).