第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問題,去搜搜看,總會(huì)有你想問的

Node JS 關(guān)閉一個(gè)讀取流

Node JS 關(guān)閉一個(gè)讀取流

UYOU 2022-06-05 09:40:40
我堅(jiān)持關(guān)閉讀取流。我正在使用 csv-parser 模塊從 CSV 文件中讀取數(shù)據(jù),進(jìn)行一些處理并將數(shù)據(jù)寫入 MongoDB。一切正常,除了我無法退出我的程序。它只是等待,我必須強(qiáng)制退出它。我怎樣才能完成它的執(zhí)行?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")在結(jié)束后添加一個(gè)事件,但這也無濟(jì)于事。
查看完整描述

3 回答

?
慕絲7291255

TA貢獻(xiàn)1859條經(jīng)驗(yàn) 獲得超6個(gè)贊

這是我解決它的方法。問題在于底層 MongoDB 連接本身。流沒有錯(cuò)。從文件中讀取記錄后,將它們插入數(shù)據(jù)庫,并在讀取并插入所有文件中的所有記錄后,關(guān)閉底層連接以結(jié)束程序。


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

  });

};


const main = async () => {

  const files = fs.readdirSync(dataPath);


  for (let i = 0; i < files.length; i++) {

    const records = await getRecordsFromFile(`${dataPath}/${files[i]}`);

    await loadRecordsToDB(getSysInfo(files[i]), records);

  }

  mongoose.connection.close();

};


main();


查看完整回答
反對(duì) 回復(fù) 2022-06-05
?
慕少森

TA貢獻(xiàn)2019條經(jīng)驗(yàn) 獲得超9個(gè)贊

對(duì)于 CLI,您必須使用 db.close() 關(guān)閉 mongodb 連接/您可以關(guān)閉。


句法:


// any other clean ups

    mongoose.connection.close(function () {

      console.log('Mongoose connection disconnected');

    });

重構(gòu)代碼:


const util = require("util");

const readDir = util.promisify(fs.readdir);

const readCSV = () => {

  return new Promise((res, rej) => {

    let records = [];

    fs.createReadStream(filePath)

      .pipe(

        csv({

          skipLines: 7,

          mapHeaders: ({ header, index }) => _.camelCase(header)

        })

      )

      .on("data", data => {

        records.push(data);

      })

      .on("error", error => {

        rej(data);

      })

      .on("end", () => {

        res(records);

      });

  });

};


const main = async () => {

  try {

    const files = await readDir(dataPath);

    await Promise.all(

      files.map(file => {

        return readCSV(`${dataPath}/${file}`) // read csv

          .then(csv => saveToDB(getSysInfo(file), csv)); // save in db

      })

    );

  } catch (error) {

    console.error(error);

  } finally {

    db.close(); // close mongo db

  }

};

main();


查看完整回答
反對(duì) 回復(fù) 2022-06-05
?
MMTTMM

TA貢獻(xiàn)1869條經(jīng)驗(yàn) 獲得超4個(gè)贊

這是對(duì)您的答案的增強(qiáng),它為 readStream 和兩個(gè)await操作添加了錯(cuò)誤處理,因此如果有任何錯(cuò)誤,您的程序仍然可以以受控方式結(jié)束并正確關(guān)閉數(shù)據(jù)庫:


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();


查看完整回答
反對(duì) 回復(fù) 2022-06-05
  • 3 回答
  • 0 關(guān)注
  • 301 瀏覽
慕課專欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)