未在函数nodejs中设置变量

时间:2019-01-09 07:16:47

标签: node.js file variables warc

我想通过解析函数中的warc文件将JSON数据分配给变量。该变量在函数外部无法访问,并在控制台上返回空数组。

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)

1 个答案:

答案 0 :(得分:0)

实际上,变量metaBobObj可以访问并且可能已设置。 问题是,在设置新变量值之前正在执行console.log语句。

我建议您阅读有关javascript中异步代码处理和变量作用域的更多信息。

这是您的固定代码:

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)
  })

有用的资料来阅读:

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://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