Home > Mobile >  Unable to get the data from fs.readfile in nodejs
Unable to get the data from fs.readfile in nodejs

Time:05-11

I am using fs to read data from a tsv file, but I am not able to access the data anywhere else in the code.

let arr;
fs.readFile('test.tsv', 'utf-8', function read(err, data) {
    if (err) {
        throw err;
    }
    arr = data.split('\t');
    
    // Able to print the data here
    console.log(arr);
})

// Not able to access the data here
for(const element of arr) {
   // rest of the code
}

I just don't want to print the data but also perform certain actions on it. Can anyone please help me out with it? Also, is there any other approach to read the data?

CodePudding user response:

You can't access arr before it exists. arr is created when the file is read. The file takes time to read. Using await, you can fix this.

var file = await fs.readFileSync('test.tsv', 'utf8');
var arr = file.split('\t');
console.log(arr);

await waits for the action to complete before moving on.

CodePudding user response:

Since the fs.readFile method is an asynchronous method, the for loop runs before this method runs, so the arr variable is not iterable, synchronous processes run before asynchronous processes. The asynchronous process is expected to take more time, so the sequencing phase is transferred to the synchronous process. To fix your problem, you can use the fs.readFileSync method, which is a synchronous alternative instead of fs.readFile, as follows:

const fs = require('fs');

let arr;
arr = fs.readFileSync('test.tsv', 'utf-8').split('\t');

// Now you are able to access the data here
for (const element of arr) {
    console.log(element);
}

Note that it is not recommended to read data from a file synchronously. The event loop can be blocked if there is a large amount of data. This may cause the server to fail to respond to other requests.

  • Related