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:
- Use the
fsPromises.readFile[]
to read the file contents into a string. - Await until the promise returned by the above method has been resolved.
- 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
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