The Node.js file system module allow the user to work with the file system on the computer.
The file I am going to read : sample.html
<html> <body> <h1>My Header h1</h1> <p>My paragraph 1.</p> <p>My paragraph 2.</p> </body> </html>
app.js - Read The HTML File with Node.js
//Node.js Built-in Module : http
//To make Node.js act as an HTTP server
const http = require('http');
//Node.js Built-in Module : fs
//To handle the file system
const fs = require('fs');
const hostname = '127.0.0.1';
const port = 3000;
const server = http.createServer((req,res) => {
//The fs.readFile() method is used to read files on the computer.
fs.readFile('sample.html',function(err,data) {
//200 means that all is OK
res.statusCode = 200;
//set header
res.setHeader('Content-Type', 'text/html');
//reads the HTML file and return the content
res.write(data);
//end of response
res.end();
});
});
//the server object listens on port XXX
server.listen(port,hostname,() => {
console.log(`Server running at http://${hostname}:${port}/`);
});
The client sends a request on the web browser : http://127.0.0.1:3000/
Output from The Program
My Header h1
My paragraph 1.My paragraph 2.
Node.js File System Module


0 留言