如何使用Node.js逐个字符地读取文件
我知道你可以用require('readline')
逐行阅读,有没有一种很好的方法来逐字符地读取文件?也许只是使用readline然后将行拆分成字符?
我想转换这段代码:
const fs = require('fs');
const lines = String(fs.readFileSync(x));
for(const c of lines){
// do what I wanna do with the c
}
希望将其变成以下内容:
fs.createReadStream().pipe(readCharByChar).on('char', c => {
// do what I wanna do with the c
});
回答如下:
简单的循环
let data = fs.readFileSync('filepath', 'utf-8');
for (const ch of data){
console.log(ch
}
使用forEach
let data = fs.readFileSync('filepath', 'utf-8');
data.split('').forEach(ch => console.log(ch)