节点:如何读取文件?

时间:2013-07-10 14:00:42

标签: javascript node.js

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

1 个答案:

答案 0 :(得分:3)

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

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
    });
});
相关问题