(Source code is at https://github.com/jauyeunggithub/rook-hotel-answers/blob/master/q3.txt)
Sometimes, we want to read a CSV text file with Node.js.
In this article, we’ll look at how to read a CSV text file with Node.js.
How to read a CSV text file with Node.js?
To read a CSV text file with Node.js, we can use the fs.readFile
method.
For instance, if we have:
foo.txt
id,name,value
1,James,50
2,Pete,300
3,Jane,400
4,Alex,200
Then we write:
const fs = require('fs')
fs.readFile('./foo.txt', (err, file) => {
const rows = file.toString().trim().split('n')
let total = 0
for (const r of rows) {
const [, , val] = r.split(',')
if (!isNaN(+val)) {
total += +val
}
}
console.log(total)
})
to import the fs
module with require
.
Then we call readFile
with the file path and a callback to get the file content from the file
parameter.
We call file.toString
to convert the contents to a string.
Then we call trim
and split
to trim and split the string by the new line character.
Next, we define total
and loop through rows
to get the value of the number column and assign to val
with destructuring.
Then we check if val
is a number with isNaN
and negation.
If it is, then we add it to total
.
Therefore, we see total
is 950 from the console log.
Conclusion
To read a CSV text file with Node.js, we can use the fs.readFile
method.