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