首页 > 解决方案 > Node JS 关闭一个读取流

问题描述

我坚持关闭读取流。我正在使用 csv-parser 模块从 CSV 文件中读取数据,进行一些处理并将数据写入 MongoDB。一切正常,除了我无法退出我的程序。它只是等待,我必须强制退出它。我怎样才能完成它的执行?

const main = () => {
  const records = [];

  fs.readdir(dataPath, (err, files) => {
    if (err) console.log("Failed to read. ", err);
    else {
      fs.createReadStream(`${dataPath}/${files[0]}`)
        .pipe(csv({ skipLines: 7, mapHeaders: ({ header, index }) => _.camelCase(header) }))
        .on("data", data => records.push(data))
        .on("end", async () => await saveToDB(getSysInfo(files[0]), records));
    }
  });
};

main();

我尝试.on("close")在结束后添加一个事件,但这也无济于事。

标签: javascriptnode.js

解决方案


Here's an enhancement on your answer that adds error handling for the readStream and for the two await operations so if there are any errors your program can still end in a controlled fashion and properly close the database:

const getRecordsFromFile = fileName => {
  return new Promise((resolve, reject) => {
    const rows = [];
    fs.createReadStream(fileName)
      .pipe(csv({ skipLines: 7, mapHeaders: ({ header, index }) => _.camelCase(header) }))
      .on("data", row => rows.push(row))
      .on("end", () => resolve(rows));
      .on("error", reject);                      // <==
  });
};

const main = async () => {
  const files = fs.readdirSync(dataPath);

  try {
    for (let i = 0; i < files.length; i++) {
      const records = await getRecordsFromFile(`${dataPath}/${files[i]}`);
      await loadRecordsToDB(getSysInfo(files[i]), records);
    }
  } catch(e) {                                             // <==
      console.log(e);                                      // <==
  } finally {                                              // <==
      // make sure we always close the connection
      mongoose.connection.close();
  }
};

main();

推荐阅读