Answers for "read html file node js"

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

show html file on nodejs code

let http = require('http');
let fs = require('fs');
 
let handleRequest = (request, response) => {
    response.writeHead(200, {
        'Content-Type': 'text/html'
    });
    fs.readFile('./index.html', null, function (error, data) {
        if (error) {
            response.writeHead(404);
            respone.write('Whoops! File not found!');
        } else {
            response.write(data);
        }
        response.end();
    });
};
 
http.createServer(handleRequest).listen(8000);
Posted by: Guest on September-02-2020
2

javascript write to file

<script> 
// Requiring fs module in which 
// writeFile function is defined. 
const fs = require('fs') 
  
// Data which will write in a file. 
let data = "Learning how to write in a file."
  
// Write data in 'Output.txt' . 
fs.writeFile('Output.txt', data, (err) => { 
      
    // In case of a error throw err. 
    if (err) throw err; 
}) 
</script>
Posted by: Guest on September-09-2020

Code answers related to "Javascript"

Browse Popular Code Answers by Language