在字符串nodejs的行上迭代

Iterate over line of string nodejs

本文关键字:迭代 字符串 nodejs      更新时间:2023-09-26

所以我有一个巨大的文本文件,看起来像:

e10_04txyscelsxeu4j63dx49b7nh3dzsn_q33_fdgskfdn_q53
e2_05txyscelsxeu4j63dx49b7nh3dzsn_q11_fdgskfdn_q13
e9_01_1txyscelsxeu4j63dx49b7nh3dzsn_q06_fdgskfdn_q42
e10_23txyscelsxeu4j63dx49b7nh3dzsn_q04_fdgskfdn_q41

有一个这些随机字符串的列表。我试图迭代每一行,获取第一个10字母/数字,并将它们吐出某个地方,这样我就可以对它们做些什么。

目前,我正在迭代每一个字母,如下所示:

const fs = require('fs');
fs.readFile('myData', 'utf8', (err, data) => {
    for (var i = 0, j = data.length; i < j; i++) {
        if (i == 10) {
            console.log('test');
        } else {
        }
    }
});

我能做我想做的事吗?

谢谢!

您可以使用readline:一次读取一行文件

// this creates a read stream 
var reader = require('readline').createInterface({
  input: require('fs').createReadStream('file.in')
});
// then here you would be able to manipulate each line:
reader.on('line', function (line) {
  console.log('The current line is: ', line);
});

您应该像@jordanhendrix所说的那样使用readline模块。

葡萄每行的前10个字符,你可以使用

line.substring(0,10);