Question

I have the following basic web server deployed using nodejitsu. I am trying to display the contents of a file. The file 'test.txt' contains a single line of plain text. I stored it on my local machine in the same folder as my 'server.js' file, than I ran jitsu deploy. The fileRead callback never seems to execute, not even the err block. Everything else runs fine. Here is the code:

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

Thanks in advance!

Était-ce utile?

La solution

You're calling res.end() synchronously, before the readFile callback executes.

You need to call res.end() after everything is finished – after you finish all of the callbacks. (whether or not an error occurred)

Autres conseils

Thanks SLaks for the answer.

Updating the code as

// 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
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top