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

111
Views
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 answers
Answer question

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 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!