1const http = require("http");
2//use fs module at first to read file
3const fs = require("fs");
4
5const hostname = "127.0.0.1";
6const port = 3000;
7// simple code to read file using fs module
8const files = fs.readFileSync("new.html");
9
10const server = http.createServer((req, res) => {
11 res.statusCode = 200;
12 // give correct input for html
13 res.setHeader("Content-Type", "text/html");
14 res.end(files);
15});
16
17server.listen(port, hostname, () => {
18 console.log(`Server running at http://${hostname}:${port}/`);
19 console.log("Done")
20});
21//simple code to make server and read file
1let http = require('http');
2let fs = require('fs');
3
4let handleRequest = (request, response) => {
5 response.writeHead(200, {
6 'Content-Type': 'text/html'
7 });
8 fs.readFile('./index.html', null, function (error, data) {
9 if (error) {
10 response.writeHead(404);
11 respone.write('Whoops! File not found!');
12 } else {
13 response.write(data);
14 }
15 response.end();
16 });
17};
18
19http.createServer(handleRequest).listen(8000);
20
1<script>
2// Requiring fs module in which
3// writeFile function is defined.
4const fs = require('fs')
5
6// Data which will write in a file.
7let data = "Learning how to write in a file."
8
9// Write data in 'Output.txt' .
10fs.writeFile('Output.txt', data, (err) => {
11
12 // In case of a error throw err.
13 if (err) throw err;
14})
15</script>