0

I'm just studying Node.JS, and i have a question over it.

I have to read a file. I do it with 'fs' node and 'fs.readFile()' func. Here is a code

const fs = require('fs');
let input;
fs.readFile('./'+config.file, (err, data) => { 
    input = data.toString('utf-8');
});

console.log(input) //!!! it gives me 'undefined' result but i expect file's data

I haven't any ideas how solve this problem. Only i know that this is the async func.

Hope, you will help me :3

Vladimir
  • 3
  • 2

2 Answers2

1

Since your code is async, your variable will be logged before the reading of the file is complete.
You can use a function and return a Promise:

const fs = require('fs');

function myReadFile() {
    return new Promise((resolve, reject) => {
        fs.readFile('myfile.txt', (err, data) => {
            if (err) reject(err);
            resolve(data.toString());
        });
    })
}

myReadFile().then((contents) => {
    console.log(contents)
});
Evya
  • 2,325
  • 3
  • 11
  • 22
0

It is asynchronous so it will first execute the synchronous code that's why input is still undefined. Synchronous code is executed first then async code. Because fs.readFile is async it will get executed after the console.log() in the event loop.

const fs = require('fs');
let input;
fs.readFile('./'+config.file, (err, data) => { 
    input = data.toString('utf-8');
    console.log(input)
});

This should log your input

More on asynchronous code in this article

Willem van der Veen
  • 33,665
  • 16
  • 190
  • 155