0

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
});
  • 1
    Possible duplicate of [Read a file one character at a time in node.js?](https://stackoverflow.com/questions/30096691/read-a-file-one-character-at-a-time-in-node-js) – TGrif Feb 18 '19 at 11:49

1 Answers1

0

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)
subhasis
  • 300
  • 1
  • 7