【问题标题】:Node.js making Request for Each line of Input File and Writing Response to Output FilesNode.js 对输入文件的每一行发出请求并将响应写入输出文件
【发布时间】:2020-01-10 01:49:30
【问题描述】:

我正在尝试读取输入文件 HA.csv,并且对于我想要发出请求 (api.getFundamentals) 并将输出写入文件的每一行。下面的代码仅适用于 csv 的一行。我在想这可能是一个同步问题。

function readLines({ input }) {
  const rl = readline.createInterface({ input });
  rl.on("line", line => {
    if(line != "Code") {
      api.getFundamentals(line).then(result => reader.writeFile(JSON.stringify(result), line + ".txt"))
    }
  });
}
const input = fs.createReadStream("HA.csv");
(async () => {
  for await (const line of readLines({ input })) {
  }
})();


//From another class
module.exports.writeFile = (data, filename) => {
    fs.writeFile(filename, data, function(err) {
      if (err) {
        return console.log(err);
      }
    });
    console.log(line);
};

正如我所说,此解决方案仅适用于输入 csv 的一行。控制台多次显示以下内容。

(node:25574) UnhandledPromiseRejectionWarning: ReferenceError: line is not defined
    at Object.module.exports.writeFile (/Users/node-stock/reader.js:44:17)
    at api.getFundamentals.then.result (/Users/node-stock/server.js:48:55)
    at process._tickCallback (internal/process/next_tick.js:68:7)
(node:25574) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 2)

【问题讨论】:

    标签: javascript node.js asynchronous request


    【解决方案1】:

    我认为你可以通过添加catch块自行找到错误原因。

    请参考以下代码。

    function readLines({ input }) {
      const rl = readline.createInterface({ input });
      rl.on("line", line => {
        if(line != "Code") {
          api.getFundamentals(line)
          .then(result => reader.writeFile(JSON.stringify(result), line + ".txt"))
          .catch(err => console.error(err))
        }
      });
    }
    
    const input = fs.createReadStream("HA.csv");
    
    (async () => {
      try {
          for await (const line of readLines({ input })) {}
      } catch(err){
          console.error(err);
      }
    })();
    
    
    //From another class
    module.exports.writeFile = (data, filename) => {
        fs.writeFile(filename, data, function(err) {
          if (err) {
            return console.log(err);
          }
        });
        console.log(line);
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-11-01
      • 2018-08-07
      • 1970-01-01
      • 2014-10-18
      • 2016-09-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多