H
H
HAbRAhabp2016-01-05 20:39:38
Node.js
HAbRAhabp, 2016-01-05 20:39:38

How to return the result of a function from a nested function?

Help please, I'm stupid in the evening. How to do the right one returnin this case? Piece of code:

function readSession (id) {
    var fs = require ("fs"),
        PHPUnserialize = require('php-unserialize');

    fs.readFile("/var/www/cookies/sess_" + id, function (err, boof) {
        if (err) throw err;

        console.log(PHPUnserialize.unserializeSession(boof.toString()));
        return PHPUnserialize.unserializeSession(boof.toString())
    })
}

app.get('/balance.json', function (req, res) {
    res.setHeader("content-type", "application/json; charset=UTF-8");
    res.send(JSON.stringify(readSession(req.cookies.PHPSESSID)));
})

console.logit is displayed normally, but nothing is displayed on the page, because the result is returned readFile, notreadSession

Answer the question

In order to leave comments, you need to log in

1 answer(s)
O
Oleg, 2016-01-05
@HAbRAhabp

It may be necessary to add a callback to readSession, it will look like this

function readSession (id,callback) {
    var fs = require ("fs"),
        PHPUnserialize = require('php-unserialize');

    fs.readFile("/var/www/cookies/sess_" + id, function (err, boof) {
        if (err) throw err;

        console.log(PHPUnserialize.unserializeSession(boof.toString()));
        callback( PHPUnserialize.unserializeSession(boof.toString()));
    })
}

app.get('/balance.json', function (req, res) {
    res.setHeader("content-type", "application/json; charset=UTF-8");
    readSession(req.cookies.PHPSESSID,function(readSession) {
       res.end(JSON.stringify(readSession));
});
   
})

I think the mistake was that you already sent a response when your function did not have time to read the file.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question