3
const fs = require('fs');
// const util = require('util');

let text = ``;

const files = [`head.txt`,`body.txt`,`leg.txt`,`feet.txt`];
let head,body,leg,feet = ``;
//const readFile = util.promisify(fs.readFile);

function isCompleted(err,data) {
    if (err) {
        throw err;
    }
    text = data.toString();
    proceedData()
}

function proceedData() {
    console.log(text);
    return text;
}

function readFileBody() {
    fs.readFile(files[1], 'utf8', isCompleted);
}

async function printFiles () {
    //head = await fs.readFile(files[0], 'utf8', (err,data) => {if (err) {throw err;}else {head += ` ${data}`}});
    body = await readFileBody();
    //await fs.readFile(files[2], 'utf8', isCompleted);
    //await fs.readFile(files[3], 'utf8', isCompleted);


}
printFiles();

When I console.log(body) in the global scope, it will return an undefined.
When I console.log(body) in the local printFile function (without return), it will return an undefined too, but I console.log(text) in local isCompleted, it will return a value of text file.

How do I store a value of text file to the variable?

Dave Newton
  • 158,873
  • 26
  • 254
  • 302

1 Answers1

13

fs.readFile does not return a promise, and even if it did, you're not returning it, that's why body is undefined. And you're mixing callbacks with promises. Either drop isCompleted or await.

To use it with await you can use util.promisify to convert a callback based function into a promise based one.

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

function readFileBody() {
    return readFile(files[1], 'utf8');
    // ^^ you need to return the promise
}

async function printFiles () {
    body = await readFileBody();
}

In node >= 10 you can use fs/promises to avoid promisify

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

function readFileBody() {
    return fs.readFile(files[1], 'utf8');
}
Marcos Casagrande
  • 37,983
  • 8
  • 84
  • 98