Raj
Raj

Reputation: 837

How to get callback value in node.js in a variable

this is my code.

var fs = require('fs')
var test = readafile('file.txt', function(returnValue) { 
    console.log(returnValue); 
    test = returnValue;
});

console.log(test);

function readafile(filepath,callback){
    var attachment_path = filepath;
    fs.readFile(attachment_path, function(err,data){
        var attachment_encoded = new Buffer(data, 'binary').toString('base64');
        callback(attachment_encoded);
    }); 
}

In that if i need that return value of that function in variable test means how to achieve that ?

In that console.log(test) it says undefined. since it is a callback function. How to get it properly ?

Upvotes: 0

Views: 105

Answers (1)

user1321425
user1321425

Reputation:

You can't really expect getting a synchronous behavior (like getting a return value) with asynchronous code. You can use fs.readFileSync to avoid the asynchronous aspect or just use your value inside your callback.
Otherwise the async module could help you out.

Upvotes: 1

Related Questions