Read a csv file on request in sapper, svelte

2.3k views Asked by At

I am new to svelte, sapper. I am trying to read a csv file located at src/_data.csv from a .js file in routes. and it gives error of no such file or directory. Can someone help to find the a way to implement it. I am trying in existing template with webpack as build-tool. Here is the structure

enter image description here

In _post.js I am trying to read a file present at the root 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)
})

My aim is to read a .csv file and convert it to JSON, possibly on every request. I know that webpack handles __dirname to / as well and there is no .csv file in __sapper__ i.e the build. But not sure how to make it work in sapper.

1

There are 1 answers

1
Rich Harris On BEST ANSWER

Since Rollup doesn't handle __dirname, you probably want to put the CSV file in a known directory outside src (e.g. data/data.csv) and read it that way:

import csv from 'csvtojson';

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

As long as the data directory is deployed with the rest of your app, and you start the app with the correct process.cwd(), this will work. (If you're just deploying the contents of __sapper__ then you may need to copy it into the deployed directory, but the basic principle is the same.)