根据要求在 sapper、svelte 中读取 csv 文件

Read a csv file on request in sapper, svelte

我是苗条的新手,工兵。我正在尝试从路径中的 .js 文件读取位于 src/_data.csv 的 csv 文件。它给出了 no such file or directory 的错误。有人可以帮助找到实现它的方法。我正在 existing template 中尝试使用 webpack 作为构建工具。这是结构

_post.js 中,我正在尝试读取存在于根 src/_data.csv 中的文件。

const csv = require('csvtojson');
const path = require("path");

const csvFilePath=path.join(__dirname, '_data.csv');
//console.log("csvFilePath", csvFilePath);
csv()
.fromFile(csvFilePath)
.then(function(data){
    console.log("json data", data)
})

我的目标是读取 .csv 文件并将其转换为 JSON,可能在每次请求时。我知道 webpack 也处理 __dirname/ 并且 __sapper__ 中没有 .csv 文件,即构建。但不确定如何让它在 sapper 中工作。

由于 Rollup 不处理 __dirname,您可能希望将 CSV 文件放在已知目录 src 之外(例如 data/data.csv) 并这样阅读:

import csv from 'csvtojson';

csv()
  .fromFile('data/data.csv')
  .then(function(data){
    console.log("json data", data)
  })

只要 data 目录与您的应用程序的其余部分一起部署,并且您使用正确的 process.cwd() 启动应用程序,这将起作用。 (如果你只是部署__sapper__的内容,那么你可能需要将其复制到部署的目录中,但基本原理是一样的。)