Node.js File System Module

Because we can’t write down all HTML page in Javascript file, we use file system module for provide HTML page which exists in server to clients.

For providing HTML page(HTMLPage.html), we need to make server javascript file like this.

1
2
3
4
5
6
7
8
9
10
11
const fs = require("fs");
const http = require("http");

http.createServer(function(request, response){
fs.readFile("HTMLPage.html", function(error, data){
response.writeHead(200, {"Content-Type:":"text/html"});
response.end(data);
});
}).listen(52273, function(){
console.log("server running at http://127.0.0.1:52273/");
});

If we want to provide another kind of file, we can change MIME type in 5th line.
For example, in jpeg case, we change text/html to image/jpeg.
It is same to other MIME types.

Examples of MIME

  • text/plain — basic text
  • text/html — HTML document
  • text/css — CSS document
  • text/xml — XML document
  • image/jpeg — JPG/JPEG image file
  • image/png — PNG image file
  • video/mpeg — MPEG video file
  • audio/mp3 — MP3 music file
Comments