1

csv file is enter image description here

and in my index.js here is my code :

    const fs = require('fs');
const csv = require('csv-parser');
const inputFile = "./data.csv"
let results = []

fs.createReadStream(inputFile)
  .pipe(csv())
  .on('data', (data) => results.push(data))
  .on('end', () => {
    console.log(results);
  });

why am i getting an error: that no such file or directory './data.csv'?

deagleshot32
  • 81
  • 1
  • 8

1 Answers1

2

When specifying file paths in node, generally relative paths are derived from the working directory from where node itself was executed. This means if you execute

node ./backEnd/index.js

The actual working directory is whatever directory is above backEnd. You can see this via console.log(process.cwd()).

If you would like to read a file relative to the current file that is being executed, you can do:

const fs = require('fs');
const path = require('path');
const csv = require('csv-parser');

const inputFile = path.resolve(__dirname, "./data.csv");
let results = []

fs.createReadStream(inputFile)
  .pipe(csv())
  .on('data', (data) => results.push(data))
  .on('end', () => {
    console.log(results);
  });

Specifically __dirname will always resolve to the directory of the javascript file being executed. Using path.resolve is technically optional here, you could manually put the path together, however using resolve is a better practice.

Rob Riddle
  • 3,544
  • 2
  • 18
  • 26