如何解析上传的 csv 文件?

时间:2021-05-19 02:17:07

标签: javascript node.js fs csv-parse

我希望我的程序允许用户上传 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 }, (err, rows) => {
        return rows;
      });
    });

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

提前感谢您的建议!

0 个答案:

没有答案
相关问题