节点:如何读取文件

Node: How to read file?

本文关键字:读取 文件 何读取 节点      更新时间:2023-09-26

我想读取一个文件,并返回作为对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的新手。

您使用的是readFile方法的同步版本。如果这是你想要的,不要给它回叫。它返回一个字符串(如果您通过编码):

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

或者(通常更合适),您可以使用异步方法(并取消编码,因为您似乎期望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
    });
});