0

我想读取一个文件并返回作为对GET请求的响应

这就是我正在做的

app.get('/', function (request, response) {
    fs.readFileSync('./index.html', 'utf8', function (err, data) {
        if (err) {
            return 'some issue on reading file';
        }
        var buffer = new Buffer(data, 'utf8');
        console.log(buffer.toString());
        response.send(buffer.toString());
    });
});

index.html

hello world!

当我加载页面localhost:5000时,页面旋转并且没有任何反应,我在这里做错了什么

我是 Node.js 的新手。

4

1 回答 1

3

您正在使用方法同步版本。如果这是您的意图,请不要将其传递给回调。它返回一个字符串(如果您传递编码):readFile

app.get('/', function (request, response) {
    response.send(fs.readFileSync('./index.html', 'utf8'));
});

或者(通常更合适)您可以使用异步方法(并摆脱编码,因为您似乎期待 a Buffer):

app.get('/', function (request, response) {
    fs.readFile('./index.html', { encoding: 'utf8' }, function (err, data) {
        // In here, `data` is a string containing the contents of the file
    });
});
于 2013-07-10T14:03:23.230 回答