首页 > 解决方案 > 如何使用 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
});

标签: node.jsreadlinefs

解决方案


简单的for循环

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)

推荐阅读