简体   繁体   中英

node.js res.write doesn't work

To learn node js i make some exercise but have got a problem, the "res" variable work in index.js but doesn't work in the fs.exists function, why ?. Thanks for your responses.

server.js

var http = require("http");
global.PATH = __dirname;

http.createServer(function(req, res) {


    var app = require("./index.js")(req, res);

    res.end();

}).listen(8080);

index.js

var url = require("url");
var fs  = require("fs");

module.exports = function(req, res){


    if(req){

        var pathname  = url.parse(req.url).pathname.split("/");
        pathname.splice(0,1);
        var action = pathname[1];


        fs.exists(PATH + "/" + pathname[0] + ".js" , function(exist){

            var controller;
            res.write('doesn\'t work');

            if(exist)
            {
                if(!controller){
                    controller = require(PATH + "/controllers/" + pathname[0] + ".js" )();

                    if(controller[action])
                        controller[action]();
                 }
            }
        });
    }
}

i don't know why some of you downvoted the question, because for a beginner some asynchronous patterns could be confusing...

first of all you should cache your require-call (as Seth mentioned).

global.PATH = __dirname;
var http = require("http");
var app = require("./index"); //omit .js, you don't need it

then you you index.js you are using fs.exists, which is asynchronous. that means, that the res.end() is called before your callback function inside fs.exists is reached, which means the request/response lifecylcle is over.

you could use fs.existsSync (not recommended!) or provide some callback which you call when done!

2 more things

  1. the if(req) is unneccessary, there is always a request object!
  2. you ALWAYS need to call the callback in your function, to make the response be sent!

server.js:

http.createServer(function(req, res) {

    app(req, res, function () {
      res.end();
    });

}).listen(8080); 

index.js:

var url = require("url");
var fs  = require("fs");

module.exports = function(req, res, cb) {  // see third cb-argument!


    var pathname  = url.parse(req.url).pathname.split("/");
    pathname.splice(0,1);
    var action = pathname[1];


    fs.exists(PATH + "/" + pathname[0] + ".js" , function(exist){

        var controller;
        res.write('doesn\'t work');

        if(exist)
        {
            if(!controller){
                controller = require(PATH + "/controllers/" + pathname[0] + ".js" )();

                if(controller[action])
                    controller[action]();
             }
        }
        cb(); // whenever you're done call the callback
    });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM