[英]Variable not set in function nodejs
I want to assign JSON data to a variable by parsing a warc file in a function. 我想通过解析函数中的warc文件将JSON数据分配给变量。 The variable is inaccessible outside a function and returns an empty array on the console.
该变量在函数外部不可访问,并在控制台上返回空数组。
var metadataObj = {
metadata: []
};
fs
.createReadStream('mywarc-file.warc')
.pipe(new WARCStreamTransform())
.on('data', record => {
if (targetURL === record.warcHeader['WARC-Target-URI']){
if(record.warcHeader['WARC-Type'] === 'response'){
metadataObj.metadata.push({
Url: record.warcHeader['WARC-Target-URI'],
WarcID:record.warcHeader['WARC-Warcinfo-ID'],
Timestamp:record.warcHeader['WARC-Date'],
ContentType:record.warcHeader['Content-Type']
})
}else{
metadataObj.metadata.push({
Host: record.httpInfo.headers['Host'],
userAgent: record.httpInfo.headers['User-Agent']
})
}
}
})
console.log(metadataObj.metadata)
Actually, the variable metadataObj is being accessible and, probably, set. 实际上,变量metaBobObj可以访问并且可能已设置。 The problem is, console.log statement is being executed before the new variable value is set.
问题是,在设置新变量值之前正在执行console.log语句。
I would recommend you to read more about async code handling and variable scopes in javascript. 我建议您阅读有关javascript中异步代码处理和变量作用域的更多信息。
Here is your code fixed: 这是您的固定代码:
var metadataObj = {
metadata: []
};
fs
.createReadStream('mywarc-file.warc')
.pipe(new WARCStreamTransform())
.on('data', record => {
if (targetURL === record.warcHeader['WARC-Target-URI']){
if(record.warcHeader['WARC-Type'] === 'response'){
metadataObj.metadata.push({
Url: record.warcHeader['WARC-Target-URI'],
WarcID:record.warcHeader['WARC-Warcinfo-ID'],
Timestamp:record.warcHeader['WARC-Date'],
ContentType:record.warcHeader['Content-Type']
})
}else{
metadataObj.metadata.push({
Host: record.httpInfo.headers['Host'],
userAgent: record.httpInfo.headers['User-Agent']
})
}
}
})
.on('end', () => {
console.log(metadataObj.metadata)
})
Useful sources to read: 有用的资料阅读:
https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous/Introducing#Asynchronous_JavaScript https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous/Introducing#Asynchronous_JavaScript
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise
https://medium.com/codebuddies/getting-to-know-asynchronous-javascript-callbacks-promises-and-async-await-17e0673281ee https://medium.com/codebuddies/getting-to-know-asynchronous-javascript-callbacks-promises-and-async-await-17e0673281ee
https://medium.com/javascript-scene/master-the-javascript-interview-what-is-a-promise-27fc71e77261 https://medium.com/javascript-scene/master-the-javascript-interview-what-is-a-promise-27fc71e77261
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.