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

112
Visualizações
How to send read txtFile content to client in Node.js with vanilla JavaScript?

I'm trying to get some data in a txt file from my server.js file, but I'm not sure how to obtain that data.

server.js:

const server = http.createServer((req, res) => {
    const { method, url } = req;
    res.status = 200;
    res.setHeader("Content-type", "text/json");
    res.setHeader("Access-Control-Allow-Origin", "*");
    res.setHeader("Access-Control-Allow-Methods", "*");
    res.setHeader("Access-Control-Allow-Headers", "*");

    if (url === "/view-stuff" && method === "GET") {
        console.log("RECIEVED GET REQ");
        let stuffReturned= fs.readFile("string.txt", (err, data) => {
            if (err) {
                throw err;
            } else {
                return data;
            }
        });
        res.writeHead(200, { "Content-Type": "text/plain" });
        res.write(stuffReturned);
    }     
res.end();
});

client.js:

function getStuffToview(){
    const request = new XMLHttpRequest();
    request.open("GET", "//localhost:1000//view-stuff", true);
    request.addEventListener("load", function () {
        try {
            console.log(this.responseText);
        } catch (e) {
            console.log(request.status);
        }
    });
    request.send();
});
}

I know it's working to some degree, because my console is logging "RECEIVED GET REQ". However, right after that's logged I get this error:

TypeError [ERR_INVALID_ARG_TYPE]: The "chunk" argument must be of type string or an instance of Buffer or Uint8Array. Received undefined.

I tried res.send(stuffReturned) instead, but it just says "res.send(stuffReturned)" is not a function.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

fs.readFile() is an asynchronous function for reading file contents. It does not return anything.

fs.readFileSync() is a synchronous read function. It returns the contents of the file being read.

A difference between the two is that fs.readFileSync blocks other operations until the read is done and content is returned, while fs.readFile does this asynchronously, allowing other operations to be done while reading the file in chunks.

Node.JS also includes Promise versions of file system methods, such as filehandle.readFile(). You can use these like so:

const fs = require("fs/promises");

(async () => {
  const stuffReturned = await fs.readFile("string.txt");
  console.log(stuffReturned); // the contents of the file
});

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