Search code examples
node.jssynchronousfile-management

Is there a way to read a text file synchronously (in JS node)?


This is my sample code:

var dicWords = []
function ReadFile()
{
    var fs = require('fs')
    fs.readFile('words_alpha_sorted.txt', (err, data) =>{
        if (err){
            console.log(err);
            return;
        }
        data = String(data)
        dicWords = data.split(/\r?\n/);
    })
}
function DoStuffWithFile();
{
    //do stuff with the variable dicWords
}
function main()
{
    ReadFile();
    DoStuffWithFile();
}

How can I can I read the file, wait for it to be completely read, then the rest of the code being executed, so that dicWords isn't an empty array when DoStuffWithFile is called? Using JS (Node). I want to call DoStuffWithFile from the main function, not ReadFile. Note-: The main function is not actually the main function, but it's where the file management is happening.


Solution

  • You can use the readFileSync function for this:

        const data = fs.readFileSync('words_alpha_sorted.txt');
    

    But the async functions are almost always a better solution. The sync methods stop Javascript execution for an unknown (compared to the JS code it seems like an eternity) amount of time, while the async filesystem functions are running in parallel.

    You can take advantage of the async/await-friendly Promise methods to do:

    var dicWords = []
    async function ReadFile()
    {
        var fs = require('fs').promises
        let data = await fs.readFile('words_alpha_sorted.txt')
        data = String(data)
        dicWords = data.split(/\r?\n/);
    }
    function DoStuffWithFile();
    {
        //do stuff with the variable dicWords
    }
    async function main()
    {
        await ReadFile();
        DoStuffWithFile();
    }