0

我希望我的程序允许用户上传 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);
  }
});

提前感谢您的任何建议!

4

0 回答 0