user3732793 user3732793 - 1 year ago 94
Javascript Question

JavaScript function return is empty after file read

this code

var fs = require("fs");
var freeApps = readFile();
console.log('4' + freeApps.toString());

function readFile () {
var content = '';
fs.readFile(__dirname + "/public/json/" + "test.json", function(err, data) {
if (err) {
return '';
console.log('1' + data.toString());
content = data;
console.log('2' + content.toString());
console.log('3' + content.toString());
return content;



where the letter is the test.json content. How could I properly read a file content and deal with it within the function ?
I succed to get the content at where 1 is and forward to another function but not within the function why is that ?

Answer Source

If you asking why your readFile function doesn't return content, which is likely since this code is off, it's because the return statement is called before the file is finished reading. This is called an "asynchronous" function because it runs in parallel with the rest of your code.

Therefore, you can't reassign content like you do here. Instead, you would need to call a function from within your callback (where your console logs 1 and 2 are) and/or make use of Promises, which are an advanced technique used to handle asynchronous behavior.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download