Q: Can't assign text to a const in Node I am trying to assign text from a txt file to a variable in node but it gives an 'undefined' error. What am I doing wrong?
const fs = require('fs');

const floor = 0;

const text = fs.readFile('./aaa.txt', (err, data) => {
    if (err) {
        console.log('errrrrroorrrrr!');
    }
    text = data.toString();
})

console.log(text);


A: You are trying to assign the same const text twice. What you can do is:
const fs = require('fs');
fs.readFile('./aaa.txt', (err, data) => {
    if (err) {
        console.log('errrrrroorrrrr!');
    }
    const text = data.toString();
    console.log(text);
})


Or, as @bhuvnesh pattnaik mentioned, you can do it like this:
let text = ``;
const textRead = fs.readFile('./aaa.txt', (err, data) => {
    if (err) {
        console.log('errrrrroorrrrr!');
    }
    text = data.toString();
});
console.log(text); //console output is ''

but be careful with this option, because the callback in readFile doesn't happen right away, and the value might still not be there when you need it.

A: First of all, you're working with callbacks, so when you do console.log, the reading operation might not be finished yet.
Another problem is that you're trying to reassign text constant. You can't reassign constants.
I would suggest using fs.readFileSync which will read your file synchronously (Do not do this if you have a big file).
const text = fs.readFileSync('./aaa.txt', 'utf8');

If you have a big file, you would have to work continue your logic inside your callback like this:
fs.readFile('./aaa.txt', (err, data) => {
    if (err) {
        console.log('errrrrroorrrrr!');
    }
    const text = data.toString();
    console.log(text);
})


A: in your code,
text is const type, so you cannot re-assign a value to it,
Either make text as let or var
OR
use another variable inside to assign the data.toString()
You should do something like below:
let text = ``;
const textRead = fs.readFile('./aaa.txt', (err, data) => {
    if (err) {
        console.log('errrrrroorrrrr!');
    }
    text = data.toString();
});


A: You should have to use it in async function only.
import fs from 'fs';
const text = await fs.promises.readFile('./aaa.txt');

