繁体   English   中英

节点:如何读取文件?

[英]Node: How to read file?

我想读取文件并返回作为对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
    });
});

暂无
暂无

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

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