gpt4 book ai didi

javascript - 如何使用流解析 Node 中的 CSV?

转载 作者:行者123 更新时间:2023-11-30 17:42:29 26 4
gpt4 key购买 nike

我有以下解析器:

function Parser(options) {  options = options || {};  // options.objectMode = true;  options.encoding = 'utf8';  Transform.call(this, options);  this._rawHeader = [];  this.header = null;}util.inherits(Parser, Transform);Parser.prototype._transform = function(data, encoding, done) {  this.push(this._parseRow(data));  done();};// Parse a data row into an objectParser.prototype._parseRow = function(row) {  var fields = row.split(";");  var obj = { code: fields[0], name: fields[1].trim() };  return obj.toString();};var parser = new Parser({});// Pipe the streamsprocess.stdin  .pipe(parser)  .pipe(process.stdout);

但是,我得到:

ACARIT21012;CASSA RURA has no method 'split'    at Parser._parseRow (/Users/pmu/projects/b/s/lib/parser.js:38:20)    at Parser._transform (/Users/pmu/projects/b/s/lib/parser.js:32:18)    at Parser.Transform._read (_stream_transform.js:179:10)    at Parser.Transform._write (_stream_transform.js:167:12)    at doWrite (_stream_writable.js:219:10)    at writeOrBuffer (_stream_writable.js:209:5)    at Parser.Writable.write (_stream_writable.js:180:11)    at write (_stream_readable.js:573:24)    at flow (_stream_readable.js:582:7)    at Socket.pipeOnReadable (_stream_readable.js:614:5)

我怀疑流中断了,但不确定如何防止这种情况发生

最佳答案

传递给 Readable 流的数据是一个 Buffer 对象,而不是一个 StringBuffer 没有split 方法。您必须对数据手动调用 toString() 才能将其作为 String 进行操作。

Parser.prototype._transform = function(data, encoding, done) {
this.push(this._parseRow(data.toString()));
done();
};

关于javascript - 如何使用流解析 Node 中的 CSV?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20774955/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com