thieumao

Load file HTML

Jan 23rd, 2017
137
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const http = require('http');
  2. const fs = require('fs');
  3. const url = require('url');
  4.  
  5. const folderPath = __dirname + '/public_files'
  6.  
  7. http.createServer( function(request, response) {
  8.   var baseURI = url.parse(request.url)
  9.   var filePath = baseURI.pathname === '/' ? folderPath + '/index.html' : folderPath + baseURI.pathname
  10.  
  11.   fs.access(filePath, fs.F_OK | fs.R_OK, function(err){
  12.     if (err) {
  13.       response.writeHead(404, {'Content-Type':'text/html'})
  14.       response.end('<h1>File not found</h1>')
  15.     } else {
  16.       fs.readFile(filePath, function(err, contenFile){
  17.         if(!err) {
  18.           response.writeHead(200, {'Content-Type':'text/html'})
  19.           response.end(contenFile)
  20.         } else {
  21.           response.writeHead(500, {'Content-Type':'text/html'})
  22.           response.end('<h1>Cannot read this content</h1>')
  23.         }
  24.       });
  25.     }
  26.   });
  27.  
  28. } ).listen(3000);
Advertisement
Add Comment
Please, Sign In to add comment