Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

113
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda