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'?

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.