Skip to content Skip to sidebar Skip to footer

Reading And Storing A Text File Into An Array With Javascript

I want to split a text file line by line, and then on encountering a character in the line (':'), to store it in an array. I need that array to plot points on a map. I can do the p

Solution 1:

This presumes that you are using the fs module of node.

The fs.readFile function is asynchronous and you correctly do the processing into lines in the callback that is called with its result.

You are however still using the processed textByLine before the callback has executed. At that point, the array would still be empty.

You can either move the textByLine.forEach part into the callback, right after splitting the file content, or switch to the synchronous version of file reading using readFileSync.

The synchronous version would return the content directly and not use a callback which is convenient, it will however block the execution of any remaining part of the script until the file has been read. This is usually bad for the user experience when processing possibly large files and therefore the asynchronous versions are preferred.

The callback does get two arguments (see the fs.readFile documentation): err and data. If err is set, it means that reading failed for some reason. The actual data is supplied as the second argument.

Last, your callback currently splits the input into lines, and then tries to split the resulting array by the ':' delimiter. But you indicate that you want each line to be split by the delimiter, so splitting the line should be done inside the textByLine.forEach callback.

Your callback could therefore be adapted like this:

function(err, text) {
    if (err) {
        // handle error somehowreturn;
    }

    text.split('\n').forEach((line) => {
        let ip = line.split(":")[0];
        addIPMarker(ip);
    }
}

Post a Comment for "Reading And Storing A Text File Into An Array With Javascript"