Home > front end >  Get the headers from a CSV file (and only that line)
Get the headers from a CSV file (and only that line)

Time:10-08

How do I read the first non-empty line from a text file, in plain javascript, possibly by using a new FileReader()?

I wish to get only the first non-empty line, not the whole text in the file (which might be enormous). By "non-empty line" I mean a line ending with \r\n and containing some non-blank char.

One of my practical goals could be to pick the first "good" line in a huge CSV file, to possibly get the "headers" (names of variables of the dataset).

The file I wish to read is now locally on my hard disk, but when the script is ready, I would also like to put it online on my domain along with the script to process it.

Thank you!

CodePudding user response:

I think you want something kinda like this:

fs = require('fs')
fs.readFile('/testFile.csv', 'utf8', function (err,data) {
  if (err) {
    return console.log(err);
  }
    var firstLineRegEx = /^(.*)$/m
    var csvHeader = firstLineRegEx.exec(data)
});

CodePudding user response:

Assuming you want to stick to client-side/in-browser JavaScript (as opposed to node.js), there's not really a way to open a file and read it line-by-line; that would require a level of direct filesystem access that's simply not available. You can certainly process it line-by-line, once it's fully-loaded and you've split it into lines.

If you want to be sure that you only ever load the first line in the browser, you'll need some server-side code for that. Node.js may or may not be a good option, depending on your existing web site.

The FileReader API you mentioned looks like it's geared towards handling arbitrary, user-provided files, which is probably the wrong direction if you'll always be in control of what file to load.

You've actually got two, distinct problems here: how do I load only part of a file in client-side JS, and how can I find the header line in a string containing CSV formatted data? (You could probably break this down differently, but it's multiple parts regardless.)

CodePudding user response:

Do you absolutely have to useFileReader? and if so, does this help? How to read CSV headers and get them in to a list in java

  • Related