Home > OS >  How to send read txtFile content to client in Node.js with vanilla JavaScript?
How to send read txtFile content to client in Node.js with vanilla JavaScript?

Time:11-05

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.

CodePudding user response:

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
});

  • Related