user5047085
user5047085

Reputation:

How to read file character by character with Node.js

I know you can read line-by-line with require('readline'), is there a good way to read a file character by character? Perhaps just use readline and then split the line into characters?

I am trying to convert this code:

const fs = require('fs');
const lines = String(fs.readFileSync(x));

for(const c of lines){
   // do what I wanna do with the c
}

looking to make this into something like:

fs.createReadStream().pipe(readCharByChar).on('char', c => {
    // do what I wanna do with the c
});

Upvotes: 0

Views: 4464

Answers (1)

subhasis
subhasis

Reputation: 298

Simple for loop

let data = fs.readFileSync('filepath', 'utf-8');
for (const ch of data){
  console.log(ch
}

Using forEach

let data = fs.readFileSync('filepath', 'utf-8');
data.split('').forEach(ch => console.log(ch)

Upvotes: -1

Related Questions