0

我使用 nodejitsu 部署了以下基本 Web 服务器。我正在尝试显示文件的内容。文件“test.txt”包含单行纯文本。我将它存储在与我的“server.js”文件相同的文件夹中的本地计算机上,而不是运行 jitsu deploy。fileRead 回调似乎永远不会执行,甚至 err 块也不会。其他一切运行良好。这是代码:

// requires node's http module
var http=require('http');
var url=require('url');
var fs=require('fs');

// creates a new httpServer instance
http.createServer(function (req, res) {
    // this is the callback, or request handler for the httpServer

    var parse=url.parse(req.url,true);
    var path=parse.pathname;
    // respond to the browser, write some headers so the 
    // browser knows what type of content we are sending
    res.writeHead(200, {'Content-Type': 'text/html'});

    fs.readFile('test.txt', 'utf8',function (err, data) {
        res.write('readFile complete');
        if(err){
            res.write('bad file');
            throw err;
        }
        if(data){
            res.write(data.toString('utf8'));
        }
    });

    // write some content to the browser that your user will see
    res.write('<h1>hello world!</h1>');
    res.write(path);

    // close the response
    res.end();
}).listen(8080); // the server will listen on port 8080

提前致谢!

4

2 回答 2

3

在 readFile 回调执行之前,您正在调用res.end() synchronously 。

你需要res.end()在一切都完成后调用——在你完成所有的回调之后。(是否发生错误)

于 2013-05-26T14:55:00.990 回答
0

感谢 SLaks 的回答。

将代码更新为

// requires node's http module
var http=require('http');
var url=require('url');
var fs=require('fs');

// creates a new httpServer instance
http.createServer(function (req, res) {
    // this is the callback, or request handler for the httpServer

    var parse=url.parse(req.url,true);
    var path=parse.pathname;
    // respond to the browser, write some headers so the 
    // browser knows what type of content we are sending
    res.writeHead(200, {'Content-Type': 'text/html'});

    fs.readFile('test.txt', 'utf8',function (err, data) {
        res.write('readFile complete');
        if(err){
            res.write('bad file');
            throw err;
            res.end();
        }
        if(data){
            res.write(data.toString('utf8'));
            // write some content to the browser that your user will see
              res.write('<h1>hello world!</h1>');
              res.write(path);
            res.end();
        }
    });





}).listen(8080); // the server will listen on port 8080
于 2014-07-02T16:21:39.520 回答