Read text file to array javascript

Using Node.js

sync mode:

var fs = require("fs");
var text = fs.readFileSync("./mytext.txt");
var textByLine = text.split("\n")

async mode:

var fs = require("fs");
fs.readFile("./mytext.txt", function(text){
    var textByLine = text.split("\n")
});

UPDATE

As of at least Node 6, readFileSync returns a Buffer, so it must first be converted to a string in order for split to work:

var text = fs.readFileSync("./mytext.txt").toString('utf-8');

Or

var text = fs.readFileSync("./mytext.txt", "utf-8");

To read a text file into an array in Node.js:

  1. Use the fsPromises.readFile() to read the file contents into a string.
  2. Await until the promise returned by the above method has been resolved.
  3. Use the split() method to split the string into an array of substrings.
const fsPromises = require('fs/promises')

const readFileAsync = async () => {
  try {
    const contents = await fsPromises.readFile('file.txt', 'utf-8')

    const arr = contents.split(/\r?\n/)

    console.log(arr)
    // [ 'this', 'is', 'an', 'example two two', 'text!' ]
  } catch (err) {
    console.error(err)
  }
}

readFileAsync()

The fsPromises.readFile() method takes the path to the file as the first parameter and the encoding as the second. It asynchronously reads the contents of the given file.

If you skip the encoding parameter, fsPromises.readFile() will return a buffer. Otherwise, a string is returned.

We used the String.split() method to split the file contents on each newline character. We did the same for reading a file line by line in Node.js.

In case you need to read the file contents synchronously, use the fs.readFileSync() method instead:

const fs = require('fs')

const contents = fs.readFileSync('file.txt', 'utf-8')

const arr = contents.split(/\r?\n/)

console.log(arr)
// [ 'this', 'is', 'an', 'example two two', 'text!' ]

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.


We can read a text file and return its content as an Array using node.js. We can use this array content to either process its lines or just for the sake of reading. We can use the 'fs' module to deal with the reading of file. The fs.readFile() and fs.readFileSync() methods are used for the reading files. We can also read large text files using this method.

Example (Using readFileSync())

Create a file with name – fileToArray.js and copy the below code snippet. After creating file, use the following command to run this code as shown in the example below −

node fileToArray.js

fileToArray.js

// Importing the fs module
let fs = require("fs")

// Intitializing the readFileLines with the file
const readFileLines = filename =>
   fs.readFileSync(filename)
   .toString('UTF8')
   .split('\n');

// Calling the readFiles function with file name
let arr = readFileLines('tutorialsPoint.txt');

// Printing the response array
console.log(arr);

Output

C:\home\node>> node fileToArray.js
[ 'Welcome to TutorialsPoint !',
   'SIMPLY LEARNING', '' ]

Example (Using async readFile())

Let's take a look at one more example.

// Importing the fs module
var fs = require("fs")

// Intitializing the readFileLines with filename
fs.readFile('tutorialsPoint.txt', function(err, data) {
   if(err) throw err;
      var array = data.toString().split("\n");
   for(i in array) {
      // Printing the response array
      console.log(array[i]);
   }
});

Output

C:\home\node>> node fileToArray.js
Welcome to TutorialsPoint !
SIMPLY LEARNING

Read text file to array javascript

Updated on 20-May-2021 13:23:16

  • Related Questions & Answers
  • Reading a Text file in java
  • Convert JS array into an object - JavaScript
  • How to read text file into a list or array with Python?
  • Different ways of Reading a file in C#
  • Reading/Writing a MS Word file in PHP
  • Reading and storing a list as an array PHP
  • How do I put a jQuery code in an external .js file?
  • Creating a Rich Text Editor in React JS
  • Reading UTF8 data from a file using Java
  • Opening and reading a file with askopenfilename in Tkinter?
  • Drag and Drop a File feature in React JS
  • Counting elements of an array using a recursive function in JS?
  • Converting a file into a byte array in SAP ABAP
  • How to use external “.js” files in an HTML file?
  • Reading and Writing CSV File using Python

How do I read a text file in node JS?

We can use the 'fs' module to deal with the reading of file. The fs. readFile() and fs. readFileSync() methods are used for the reading files.

How do I read a text file in react JS?

To read a text file in React, we can use the FileReader constructor. to define the showFile function that gets the selected file from e. target.

How do I open a JS file?

How to Open a File in Javascript.
Right-click the HTML file you want to use to open the file. Click "Open With," then double-click the preferred JavaScript editor. ... .
Create the JavaScript function. ... .
Add the function to the "Browse" button on the Web page. ... .
Save the file and open it in your default Web browser..

How do you write to a file in JavaScript?

Import fs-module in the program and use functions to write text to files in the system. The following function will create a new file with a given name if there isn't one, else it will rewrite the file erasing all the previous data in it. Used Function: The writeFile() functions is used for writing operation.