Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

returning undefined from readFile [duplicate]

I'm trying to get the following code to work:

'use strict';

var fs = require('fs');

var fileName = 'readme.txt';
var str = fs.readFile(fileName, 'utf8', function (err, data) {
    if (err) {
        console.log(err);
        throw err;
    }
    return data;
});

console.log('result read: ' + str);

readme.txt:

console.log('working');

I'm trying to display the following:

result read: console.log('working');
like image 869
basickarl Avatar asked Jan 24 '16 19:01

basickarl


2 Answers

readFile is executed asynchronously, so data can only be accessed inside the callback function, if you want it to be synchronous, you should use readFileSync

Async:

'use strict';

const fs = require('fs');

const fileName = 'readme.txt';
fs.readFile(fileName, 'utf8', function (err, data) {
   if (err)
      return console.log(err);
   console.log('result read: ' + data);
});

Sync:

var str = fs.readFileSync(fileName, 'utf8'); // This will block the event loop, not recommended for non-cli programs.
console.log('result read: ' + str);

UPDATE

You can use util.promisify to convert fs.readFile from callback API to promise API.

const fs = require('fs');
const { promisify } = require('util');
const readFile = promisify(fs.readFile);

(async() =>  {
   try {
      const result = await readFile('readme.txt', 'utf8');
      consle.log(result);
   } catch(e) {
      console.error(e);
   }
})();

In Node 10 you can use fs/promises and avoid util.promisify

const fs = require('fs').promises;

(async() =>  {
   try {
      const result = await fs.readFile('readme.txt', 'utf8');
      consle.log(result);
   } catch(e) {
      console.error(e);
   }
})();
like image 154
Marcos Casagrande Avatar answered Sep 23 '22 00:09

Marcos Casagrande


You're calling an asynchronous function. This means it does not wait to return when called and will, in this case, return undefined.

You can either use the readFileSync method to call it synchronously, or put your console.log in the callback

like image 28
Joseph Young Avatar answered Sep 23 '22 00:09

Joseph Young