Node.js as a Web Server


myModule.js

//Use the exports keyword to make properties and methods available outside the module file.

exports.nowDate=function()
{
    var date=new Date();
    
    //https://www.w3schools.com/jsref/jsref_obj_date.asp
    return date.getFullYear() + "/" + (date.getMonth()+1) + "/" + date.getDate() + " " + date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds();
}

app.js

//Include Node.js Built-in Modules
//HTTP module allows Node.js to transfer data over the Hyper Text Transfer Protocol (HTTP).
const http = require('http');

//To parse URL strings
const url = require('url');

//Include Your Own Module
//use ./ to locate the module, that means that the module is located in the same folder as the Node.js file
const myModule=require('./myModule');

const hostname = '127.0.0.1';
const port = 3000;

//HTTP module can create an HTTP server that listens to server ports and gives a response back to the client.
//Use the createServer() method to create a server object:

const server = http.createServer((req, res) => {

  //200 means that all is OK
  res.statusCode = 200;

  res.setHeader('Content-Type', 'text/html');

  //This req object has a property called "url" which holds the part of the url that comes after the domain name:
  res.write('the part of the url that comes after the domain name: ' + req.url + '');

  var queryObj=url.parse(req.url,true).query;

  //if the url is http://127.0.0.1:3000/?name=Peter
  var name=queryObj.name;

  if(name!=undefined)
  {
    res.write('name : ' + name + '')
  } 

  //write a response to the client
  res.write('The date and time are currently: ' + myModule.nowDate() + '');

  res.end('end the response');
  
});

//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/?name=Peter

Output from The Program

the part of the url that comes after the domain name: /?name=Peter
name : Peter
The date and time are currently: 2018/2/26 17:37:20
end the response


Node.js Modules

Node.js HTTP Module

張貼留言

0 留言