如何在节点js中将async / await与fs.createReadStream一起使用

时间:2019-10-17 11:01:10

标签: javascript node.js

我有node js服务,该服务读取csv文件并根据提供的参数过滤记录。我需要等到文件读取处理完毕后才能等待。我尝试使用async / await和promise,但是没有运气。

如何等待文件处理完毕并返回json响应。

app.get('/getEmpInfo/:emailId/:unique_code', async (req,res) => {
    console.log("req.params.emailId :"+req.params.emailId);
    console.log("req.params.unique_code :"+req.params.unique_code);
    const response = await getEmpDetailsByEmailIdAndUniqueCode(req.params.emailId,req.params.unique_code);
    res.send(response)
}); 

async function getEmpDetailsByEmailIdAndUniqueCode(emailId,uniqueCode){
    console.log("inside getEmpDetailsByEmailIdAndUniqueCode()::"+emailId+"::"+uniqueCode);
    var fetchData = [];

    // try 1
/*  await fs.createReadStream(investorFileName1)
      .pipe(csv())
      .on('data', (row) => {
        if(row.unique_code != null && row.unique_code == uniqueCode && row.investor_email_id == emailId) {
            fetchData.push(row);
            console.log(row);
        }
      })
      .on('end', () => {
        console.log('CSV file successfully processed');
        console.log(fetchData);
    }); */

  // try 2
    var response = fs.createReadStream(fileName).pipe(csv());

    return new Promise(function(resolve,reject){
        response.on('end', () => resolve(fetchData));
        response.on('error', reject); 
    })
}

2 个答案:

答案 0 :(得分:1)

您非常亲密。只需将您的2种实现合并为第3种:

async function getEmpDetailsByEmailIdAndUniqueCode(fileName,emailId,uniqueCode){
    console.log("inside getEmpDetailsByEmailIdAndUniqueCode()::"+emailId+"::"+uniqueCode);

    return new Promise(function(resolve,reject){
        var fetchData = [];
        fs.createReadStream(fileName)
            .pipe(csv())
            .on('data', (row) => {
                if(row.unique_code != null && row.unique_code == uniqueCode && row.investor_email_id == emailId) {
                    fetchData.push(row);
                    console.log(row);
                }
            })
            .on('end', () => {
                console.log('CSV file successfully processed');
                console.log(fetchData);
                resolve(fetchData);
            })
            .on('error', reject); 
    })
}

请注意,我添加了fileName作为第一个参数,因为在代码中的任何地方都看不到它。

我也没有测试它,只是将您的代码粘在一起:)。

答案 1 :(得分:1)

请使用下面的代码

const getEmpDetailsByEmailIdAndUniqueCode = () => {
 return new Promise((resolve, reject) => {
  const fetchData = [];
let stream = fs.createReadStream(investorFileName1);
stream.on("error", err => reject(err));
stream.on('data', (row) => {
    if(row.unique_code != null && row.unique_code == uniqueCode && 
        row.investor_email_id == emailId) {
        fetchData.push(row);
        console.log(row);
    }
  })
stream.on("end", () => resolve(fetchdata));
 });
}