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

218
Views
Is there a Node.js function to read the contents of a file on a server?

My initial question got marked as a duplicate for a completely unrelated question that has absolutely nothing in common with my question, so I'm reposting this with some clarifications that should hopefully make it clearer what I want to do.


Suppose I have a file on a server that is NOT my server:

https://example.com/names.txt

Is there a function such that I can read this file as a String or as a Buffer?

The obvious solution would be to download the file into a temporary directory, read its contents, then delete it, but this is very slow and takes many lines of code. Is there a cleaner way to do this?

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

0

You'd have to make a request to that server for that file. (e.g. a GET request) using the module of your choice.

Making a request with the HTTP module

Note: in the example, d in the on('data', ...) callback will be what you want.

about 4 years ago · Juan Pablo Isaza Report

0

Assuming the file is on an http server, you can use one of the http request modules listed here to make a request for that file. The usual default behavior is to get the response from the http server into memory, though you can put it in a file if you want.

The built-in http library can do this, but it takes more lines of code than the higher level libraries in my link above which is their main benefit.

Here's a simple example using my favorite choice for this type of library the got module (which has built-in promise support):

const got = require('got');
got("https://someserver.com/somefile.txt").text().then(result => {
    console.log(result);
}).catch(err => {
    console.log(err);
});

The got library has methods .text(), .json() and .buffer() for fetching the response body, parsing it (if necessary) and putting the result into the right type of variable. My example above uses .text() since you mentioned getting the response into a string. If you want it in a buffer, you would use .buffer() instead.

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!