js中用数组读取html文件,js:读取一个文本文件转换成一个数组。(每行一个数组中的项)。...

chacko提出了一个问题:node.js: read a text file into an array. (Each line an item in the array.),或许与您遇到的问题类似。

回答者mtomis给出了该问题的处理方式:

If you can fit the final data into an array then wouldn't you also be able to fit it in a string and split it, as has been suggested? In any case if you would like to process the file one line at a time you can also try something like this:

var fs = require('fs');

function readLines(input, func) {

var remaining = '';

input.on('data', function(data) {

remaining += data;

var index = remaining.indexOf('\n');

while (index > -1) {

var line = remaining.substring(0, index);

remaining = remaining.substring(index + 1);

func(line);

index = remaining.indexOf('\n');

}

});

input.on('end', function() {

if (remaining.length > 0) {

func(remaining);

}

});

}

function func(data) {

console.log('Line: ' + data);

}

var input = fs.createReadStream('lines.txt');

readLines(input, func);

EDIT: (in response to comment by phopkins) I think (at least in newer versions) substring does not copy data but creates a special SlicedString object (from a quick glance at the v8 source code). In any case here is a modification that avoids the mentioned substring (tested on a file several megabytes worth of "All work and no play makes Jack a dull boy"):

function readLines(input, func) {

var remaining = '';

input.on('data', function(data) {

remaining += data;

var index = remaining.indexOf('\n');

var last = 0;

while (index > -1) {

var line = remaining.substring(last, index);

last = index + 1;

func(line);

index = remaining.indexOf('\n', last);

}

remaining = remaining.substring(last);

});

input.on('end', function() {

if (remaining.length > 0) {

func(remaining);

}

});

}

希望本文对你有帮助,欢迎支持JavaScript中文网

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值