Search code examples
node.jscsv-parser

csv-parser cannot read or open such .csv file


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


Solution

  • 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.