0

Here is my code: const fs = require('fs');

function f() {
  var arr = [];
  fs.readfile(filename, function(data) {
    //some code here
    arr.push(someElement);
  })
  return arr;
}


var result = f();
console.log(result);
//I want an array of elements in it, but this produces an empty array []; 

Any help would be very appreciated!

shaogu
  • 3
  • 2
  • 1
    Did you mean to use `readfileSync` and not `readfile`? - `readfile` is async which means you can't mutate an array like that. – evolutionxbox Feb 23 '20 at 16:55
  • 1
    Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – evolutionxbox Feb 23 '20 at 16:55

1 Answers1

0

You need to use readfileSync in order to make your function synchronous, or do this:

function f() {
  var arr = [];
  fs.readfile(filename, function(data) {
    //some code here
    arr.push(someElement);
  }).then(() => return arr)
}

f().then(result => console.log(result));

Adding @artur 's addition here:

readFile(), receives a function that is a callback. As specified in the doc, readFile: Asynchronously reads the entire contents of a file. So, the callback function OP gave to readFile will not be immediately called, only when the file data is ready.

Tasos
  • 1,880
  • 13
  • 19
  • 1
    To add to this: [`readFile()`](https://nodejs.org/api/fs.html#fs_fs_readfile_path_options_callback), receives a function that is a callback. As specified in the doc, readFile: `Asynchronously reads the entire contents of a file.` So, the callback function OP gave to `readFile` will not be immediately called, only when the file `data` is ready. – Artur Feb 23 '20 at 16:59