0

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 ?

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.