如何解析上传的 csv 文件?

问题描述

我希望我的程序允许用户上传 CSV 文件并让它更新数据库中的相关表。

我已成功设置上传部分,但我一直无法弄清楚如何解析 CSV 以允许插入查询

router.post("/upload",async (req,res,next) => {
  try {
    //  My plan:
    //  Parse uploaded csv file into an array of arrays
        //  Read csv through fs
        //  Parse data with csv-parse
    //  Insert array into postgres db using knex

    const inputPath; // I can access the csv file in req.files.myFile,but it looks like fs.readFile needs a file path,rather than the file itself?

    const tableName = req.files.myFile.name.split(".")[0];

    // I think it might be something like this? 
    // But I also feel like I should be able to directly parse the csv file?
    let data = await fs.readFile(inputPath,(err,fileData) => {
      parse(fileData,{ columns: false,trim: true },rows) => {
        return rows;
      });
    });

    await insertData(data,tableName);
    await res.send("table updated!");
  } catch (error) {
    console.log("Error:",error);
    next(error);
  }
});

提前感谢您的建议!

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)