Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

198
Views
Get the headers from a CSV file (and only that line)

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!

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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)
});
about 4 years ago · Juan Pablo Isaza Report

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!