node.js - 如何使用 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
});
解决方案
简单的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)
推荐阅读
- python - 连接变量和字符串python脚本
- r - R中的匿名函数没有返回预期的输出
- java - 扎实的 Java 开发人员中的 Java 死锁示例
- arrays - 将过滤器应用于具有数值的列
- jquery - 如何使按钮组表现得像按钮阶段
- html - 表单字段 a 未显示在 html 页面 django 上
- python - 有人可以用这个 ImportError 在 django 上帮助我吗:无法从 'products.views' 导入名称 'product_detial_view'
- firebase - firebase/firestore 中复杂的数据结构
- android - 如果没有调用 stopservice(),内存泄漏?
- firebase - 是否可以检查文档在 Firestore 中是否有子集合?