0

What's the most efficient way to take the outcome of the 'readFile' method below to the global context so I can use the response in other funcionalities? I've tried several ways to do so but not success.

const fs = require('fs');  
var response = '';

fs.readFile('test.txt', 'utf8', (err,data) => {
    if (err) throw err;
    response += data;
})

console.log(response) // prints '', it does not update the value 
  • This isn't possible. You'll need to chain from the callback or uses promises for any code that depends on `data`. Or use `readFileSync` but that's generally not advisable because you block the main thread on I/O and it can't do other tasks. – ggorlen Jan 20 '22 at 14:31
  • You need to learn what is callback and promise, how they work and how to use them. – digitalniweb Jan 20 '22 at 14:32

1 Answers1

-1

Your problem is that you treat Node as a synchronous / sequential language.

I recommend that you learn about callbacks (you use it here), Promises and async / await. (And TypeScript by the way)

Fortunately, with node v10 you can easily avoid the pitfalls of async and * callback hell * - using async / await

A modern solution should look similar to:

import { readFile } from 'fs/promises'; //Modern fersion of `fs`

const main = async () => { // modern way to define function (async)
  let response = ''; // Variables defined by `var` are available in global context, and may cause problems 
  response = await readFile('test.txt', {encoding: 'utf8' })
  return response
}

try { // `try {} catch() {}` - error handling
  console.log(await main())//It will work 90% of the time.
} catch (ex) {
  console.error(ex)
}

//If you cannot define an asychronic function then use: 
main().then((res) =>{
  console.log(res)
  //Here you can use `res`
}).catch(ex => console.error(ex)) // error handling
// not here

bato3
  • 2,695
  • 1
  • 18
  • 26