0

I have this sample on node version 4.2.1:

'use strict';

const fs = require('fs');

function getFilesizeInBytes(filename) {
    fs.stat(filename, (err, stats) => {
        if (err) throw err;
        console.log('inner: ' + stats.size);
        return stats.size;
    }); }

console.log('outer: '+ getFilesizeInBytes(__filename));

As result I have this output:

outer: undefined
inner: 325

Why outer is 'undefined'? How to fix it?

vinayakj
  • 5,591
  • 3
  • 28
  • 48
karl
  • 215
  • 1
  • 2
  • 9
  • `fs.stat` is async, it hasn't returned anything by the time you do `console.log('outer: '+ getFilesizeInBytes(__filename));` – brbcoding Oct 29 '15 at 21:43
  • use the data `stats` in callback function, as its Async, it wont be available immediately and you cant predict when it can be available that is why callback functions are provided. – vinayakj Oct 29 '15 at 21:56
  • This is a very common question here and thus there are lots of prior answers that address the issue. In a nutshell, your code is not executed line by line in order. The callback for `fs.stat()` is asynchronous and thus is called someone LATER by the file system infrastructure, long after `getFilesizeInBytes()` has already returned. So, returning a value from that callback just goes back into the file system infrastructure and not back to your function. – jfriend00 Oct 29 '15 at 22:04

0 Answers0