Linux uses Node. js to establish a service instance for accessing static web pages

  • 2021-08-05 08:43:02
  • OfStack

Linux uses Node. js to establish a service instance for accessing static web pages

1. Install the environment required for node. js to run: https://www.ofstack.com/article/79536. htm

2. Create the node directory (/node/www) and create the node. js service file server. js under the directory


var http = require('http');

var fs = require('fs');// Introducing file reading module 

var documentRoot =  ' /node/www';// The directory where the files to be accessed are stored 

var server= http.createServer(function(req,res){

  var url = req.url; 
  // Client-entered url For example, if you enter localhost:9999/index.html
  // So here's url == /index.html

  var file = documentRoot + url;
  console.log(url);//node/www/index.html 
  
  /*
    file Is the file path 
    function Is a callback function ,
    function Adj. err To read the information returned by the error, if you return null, there will be no error 
    function Adj. data Text content returned for successful reading 
  */
  fs.readFile( file , function(err,data){
    if(err){
      res.writeHeader(404,{
        'content-type' : 'text/html;charset="utf-8"'
      });
      res.write('<h1>404 Errors </h1><p> The page you are looking for does not exist </p>');
      res.end();
    }else{
      res.writeHeader(200,{
        'content-type' : 'text/html;charset="utf-8"'
      });
      res.write(data);// Will index.html Display on the client 
      res.end();
    }

  });

}).listen(9999);

console.log(' Server started successfully ...');

3. Create an index. html homepage file under Path/node/www/

4. Start service command: node server. js

5. Browser input address: http://localhost: 9999/index. html

Thank you for reading, hope to help everyone, thank you for your support to this site!


Related articles: