Home > Back-end >  Is there a Node.js function to read the contents of a file on a server?
Is there a Node.js function to read the contents of a file on a server?

Time:12-09

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?

CodePudding user response:

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.

CodePudding user response:

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.

  • Related