2013-05-26 47 views
0

我使用nodejitsu部署了以下基本Web服務器。我正在嘗試顯示文件的內容。文件'test.txt'包含一行純文本。我將它存儲在我的本地機器上與我的'server.js'文件相同的文件夾中,而不是我運行jitsu deploy。 fileRead回調似乎永遠不會執行,甚至不是err塊。其他一切運行良好。這裏是代碼:node.js fs.fileRead無法正常工作

// 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 

在此先感謝!

回答

3

在執行readFile回調之前,您正在同步調用res.end()

在完成所有回調之後,您需要在完成所有操作後–之後致電res.end()。 (是否發生錯誤)

+0

好,我看到的。謝謝! – gloo

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