【问题标题】:How to await fs.createReadStrem?如何等待 fs.createReadStrem?
【发布时间】:2021-09-08 02:19:24
【问题描述】:

我有这个代码

router.post("/uploads", multer(multerConfig).single('file'), async (req, res) => {

// SOME CODE
count = 0;

try { 
    let connection
    connection = await oracledb.getConnection(dbConfig.dbAlarm);

    fs.createReadStream(filePath)
        .pipe(parse({
          delimiter: [';'],
          }), 
          column: true,
          bom: true, 
          trim: true
        })
      ).on('data', function(csvrow) {
          count = count + 1;
          console.log(count);
          })
       .on('end', async function() {
        // SOME CODE TO SELECT AND INSERT IN DATABASE
        })
       .on('close', () => {
          fs.unlink(filePath, (err) => {
            if (err) {
              throw err;
            }
            console.log("File is deleted.");
          });
        });

    res.status(200).json({rows: count})

问题是,在我的回复中,我总是得到 0。在我的 console.log(count) 中,我可以完美地看到我的 csv 的所有行。如何获得实际的行数?我怎样才能“等待” fs?

【问题讨论】:

  • 使用pipeline() 而不是.pipe() 然后就可以等待整个操作了。请参阅示例here

标签: node.js express async-await fs


【解决方案1】:

您可以重构并使用 cmets 中提到的 pipeline,但如果您只想等待当前进程,您也可以将其包装在一个 Promise 中。像这样的东西应该适合你:

try { 
    let connection
    connection = await oracledb.getConnection(dbConfig.dbAlarm);

    let count = await insertFileIntoDB(filePath)

    res.status(200).json({rows: count})
}

    
function insertFileIntoDB(filePath){
    return new Promise((resolve,reject)=>{
        let count = 0
        fs.createReadStream(filePath)
        .pipe(parse({
          delimiter: [';'],
          }), 
          column: true,
          bom: true, 
          trim: true
        })
      ).on('data', function(csvrow) {
          count = count + 1;
          console.log(count);
          })
       .on('end', async function() {
        // SOME CODE TO SELECT AND INSERT IN DATABASE
        })
       .on('close', () => {
          fs.unlink(filePath, (err) => {
            if (err) {
              reject(err);
            }
            console.log("File is deleted.");
            resolve(count)
          });
        });
        
        
    })
}

【讨论】:

  • 非常感谢!
猜你喜欢
  • 1970-01-01
  • 2019-12-15
  • 1970-01-01
  • 2021-08-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-17
相关资源
最近更新 更多