2013-05-26 4 views
0

У меня есть следующий базовый веб-сервер, развернутый с помощью nodejitsu. Я пытаюсь отобразить содержимое файла. Файл test.txt содержит одну строку простого текста. Я сохранил его на своем локальном компьютере в той же папке, что и файл «server.js», чем я запускал jitsu deploy. Обратный вызов fileRead никогда не выполняется, даже блок err. Все остальное работает нормально. Вот код:node.js fs.fileRead not working

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

Вы звоните res.end()синхронно, перед выполнением обратного вызова readFile.

Вам необходимо позвонить по телефону 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