Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

217
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda