【发布时间】:2020-11-13 17:01:21
【问题描述】:
我正在尝试获取一个简单的流来读取和解析 JSON 并将对添加到哈希表中。最终我将把它作为一个模块导出到另一个程序中使用,但在调试时我遇到了这个错误:
this.hashtable.put(data['word'], data['rate']);
^
TypeError: Cannot read property 'put' of undefined
at Stream.<anonymous> (/mnt/c/users/joeys/Desktop/RumbleUp/message-data/dev/test/test-stream.js:18:22)
at Stream.emit (events.js:315:20)
at drain (/mnt/c/users/joeys/Desktop/RumbleUp/message-data/dev/node_modules/through/index.js:36:16)
at Stream.stream.queue.stream.push (/mnt/c/users/joeys/Desktop/RumbleUp/message-data/dev/node_modules/through/index.js:45:5)
at Parser.parser.onValue (/mnt/c/users/joeys/Desktop/RumbleUp/message-data/dev/node_modules/JSONStream/index.js:118:16)
at Parser.proto.emit (/mnt/c/users/joeys/Desktop/RumbleUp/message-data/dev/node_modules/jsonparse/jsonparse.js:337:8)
at Parser.proto.pop (/mnt/c/users/joeys/Desktop/RumbleUp/message-data/dev/node_modules/jsonparse/jsonparse.js:332:8)
at Parser.proto.onToken (/mnt/c/users/joeys/Desktop/RumbleUp/message-data/dev/node_modules/jsonparse/jsonparse.js:402:12)
at Parser.parser.onToken (/mnt/c/users/joeys/Desktop/RumbleUp/message-data/dev/node_modules/JSONStream/index.js:128:12)
at Parser.proto.write (/mnt/c/users/joeys/Desktop/RumbleUp/message-data/dev/node_modules/jsonparse/jsonparse.js:135:34)
这是我的简单脚本:
var JSONStream = require('JSONStream')
var fs = require('fs');
var Hash = require('simple-hashtable');
function obj() {
this.hashtable = new Hash();
console.log(this.hashtable.isEmpty());
this.hashtable.put('yo', 'response');
this.stream = fs.createReadStream('./output-1.json', { encoding: 'utf8' }).pipe(JSONStream.parse('*'));
this.read = function(){
this.stream.on('data', function(data){
console.log(data['word']);
this.hashtable.put(data['word'], data['rate']);
//console.log(this.hashtable.get(data['word']));
});
}
}
var temp = new obj();
temp.read();
JSON 文件通常非常大,因此是流,但在此测试中,它只是这样:
[{
"word": "Co",
"rate": 0.20654307524536533
},{
"word": "Issac",
"rate": 0.08174386920980926
},{
"word": "httpsaswarus",
"rate": 0.12835820895522387
},{
"word": "values",
"rate": 0.2151509086923788
}]
当我调试时,哈希表构造得很好并且不是未定义的。读取功能之外的这种方法都可以正常工作。当我删除导致错误的行时,一切都打印得很好。我只是不明白为什么如果在这两种方法中工作正常,表会是未定义的。我觉得我错过了什么。如果有人对解决此问题有任何见解,将不胜感激!
这里是我用来参考的包的链接:
【问题讨论】:
-
这能回答你的问题吗? How does the "this" keyword work?
标签: javascript node.js npm typeerror hashtable