Answers for "how to read html file data in node js using fs"

1

read html file node js

const http = require("http");
//use fs module at first to read file 
const fs = require("fs");

const hostname = "127.0.0.1";
const port = 3000;
// simple code to read file using fs module
const files = fs.readFileSync("new.html");

const server = http.createServer((req, res) => {
  res.statusCode = 200;
  // give correct input for html
  res.setHeader("Content-Type", "text/html");
  res.end(files);
});

server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
  console.log("Done")
});
//simple code to make server and read file
Posted by: Guest on December-12-2020
1

read file in nodejs using fs

let myFile = "./myText.txt";
const fs = require("fs");
		
app.all('/test', async (req, res) => {
	try {
		const readData = fs.readFileSync(myFile, 'utf8');
		if (readData) {
			res.send(readData)
		}
	} catch (error) {
		res.send("something is wrong", error)
	}
})
Posted by: Guest on January-07-2021

Code answers related to "Javascript"

Browse Popular Code Answers by Language