node.js – websockets – socket.io

This is a practical guide about use websockets with node.js in locahost.

WebSocket is a computer communications protocol, providing full-duplex communication channels over a single TCP connection. (https://en.wikipedia.org/wiki/WebSocket)

A WebSocket is a persistent connection between a client and server and is perfect for chat, social applications, games, in general realtime communication applications.

websocket-bidirectional-messages

Data transfer is cery efficient, one HTTP request and response took a total of 282 bytes while the request and response websocket frames weighed in at a total of 54 bytes (31 bytes for the request message and 24 bytes for the response).

websocket-data-transfer

Ok, i’ll stop annoing you, let’s start coding 😀

Start your localhost environement, mine is Laragon

1. Create a new folder for this app laragon/www/websockets

2. Open the Laragon’s Cmder in laragon/www/websockets and type: node -v
If it is running you have node.js working in your system

3. Type: npm install socket.io
Install the module to manage Websocket

4. Create laragon/www/websockets/app.js
This is the main js file of you app

var http = require('http');
var fs = require('fs');

// a. Load index.html 
var server = http.createServer(function(req, res) {
  fs.readFile('./index.html', 'utf-8', function(error, content) {
    res.writeHead(200, {"Content-Type": "text/html"});
    res.end(content);
  });
});

// b. Load Socket.io, socket.io listen to server = http.createServer...
var io = require('socket.io').listen(server);

// c. When a client connect write a message in console
io.sockets.on('connection', function (socket) {
  console.log('New user connected');
  socket.emit('message', 'You are connected!');

// In case of an event "message" from client
  socket.on('message', function (message) {
      console.log('The client say:' + message);
  });
});

server.listen(8080);

The actions in order are:
a. create a classic http connection to load index.html
b. open, using Websocket a tunnel between client and server, this will be now a stable full duplex connection
c. check in console the success of the handshake and send a message to client

5. Create laragon/www/websockets/index.html
This is the client side rendered by the browser

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8" />
  <title>Socket.io</title>
</head>
<body>
  <h1>Using Socket.io!</h1>

  <p>
    <input type="button" value="Poke" id="poke" />
  </p>
  <script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
  <script src="/socket.io/socket.io.js"></script>
  <script>
  var socket = io.connect('http://localhost:8080');
  socket.on('message', function(message) {
    alert('The server says: ' + message);
  });

  $('#poke').click(function () {
     socket.emit('message', 'Server listen to me!');
   })
  </script>
</body>
</html>

The connection with the WebSocket is:

<script src="/socket.io/socket.io.js"></script>
  <script>
  var socket = io.connect('http://localhost:8080');
  </script>

It is important put this JS near to not interfere with the loadind of the page

6. Time to test the code, type in terminal: node app.js
Start the server

7. Connect the browser at localhost:8080
Look the terminal, it will say: New user connected
Look at the browser, it will open an alert with the server message -> this in the message from server
Push the button Poke, the terminal will receive Server listen to me! -> this in the message from client

Notice about socket.emit()

// emit one parameter only
// parameter can be everything: player_score, player_chat, player_scores
socket.emit('message', 'You are connected!');

// emit supports multiple parameter too
socket.emit('message', { content: 'You are connected!', importance: '1' });

BROADCAST

Broadcasting is the distribution of some content to a dispersed audience using WebSockets.

broadcast-socket-io

Take the previous code and change it as show below

laragon/www/websockets/app.js

var http = require('http');
var fs = require('fs');
 
// a. Load index.html 
var server = http.createServer(function(req, res) {
  fs.readFile('./index.html', 'utf-8', function(error, content) {
    res.writeHead(200, {"Content-Type": "text/html"});
    res.end(content);
  });
});
 
// b. Load Socket.io, socket.io listen to server = http.createServer...
var io = require('socket.io').listen(server);
 
// c. When a client connect write a message in console
io.sockets.on('connection', function (socket) {
  console.log('New user connected');
  socket.emit('message', 'You are connected!');
  socket.broadcast.emit('messagebroadcast', 'New user connected');
 
// In case of an event "message" from client
  socket.on('message', function (message) {
      console.log('The client say:' + message);
  });
});
 
server.listen(8080);

laragon/www/websockets/index.html

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8" />
  <title>Socket.io</title>
</head>
<body>
  <h1>Using Socket.io!</h1>
 
  <p>
    <input type="button" value="Poke" id="poke" />
  </p>
  <script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
  <script src="/socket.io/socket.io.js"></script>
  <script>
  var socket = io.connect('http://localhost:8080');
  socket.on('message', function(message) {
    alert('The server says: ' + message);
  });
  socket.on('messagebroadcast', function(messagebroadcast) {
    alert('Broadcast message: ' + messagebroadcast);
  });
 
  $('#poke').click(function () {
     socket.emit('message', 'Server listen to me!');
   })
  </script>
</body>
</html>

Notice the code:

// server
socket.broadcast.emit('messagebroadcast', 'New user connected');

// client
socket.on('messagebroadcast', function(messagebroadcast) {
    alert('Broadcast message: ' + messagebroadcast);
  });

Now at every new connection, all clients will be informed via an alert window 😀

CLIENT IDENTIFICATION

We need to identify a client to create a real life app.
Change the code as shown below:

laragon/www/websockets/app.js

var http = require('http');
var fs = require('fs');
 
// a. Load index.html 
var server = http.createServer(function(req, res) {
  fs.readFile('./index.html', 'utf-8', function(error, content) {
    res.writeHead(200, {"Content-Type": "text/html"});
    res.end(content);
  });
});
 
// b. Load Socket.io, socket.io listen to server = http.createServer...
var io = require('socket.io').listen(server);
 
// c. When a client connect write a message in console
io.sockets.on('connection', function (socket) {
	
  // anonym user
  console.log('Anonym user connected');
  
  // know user
  socket.on('newbie', function(username) {
    socket.username = username; // store the userID here
	console.log('Username: ' + socket.username + ' connected!');
	socket.emit('message', 'You are connected as' + socket.username);
  });
 
});
 
server.listen(8080);

laragon/www/websockets/index.html

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8" />
  <title>Socket.io</title>
</head>
<body>
  <h1>Using Socket.io!</h1>
 
  <p>
    <input type="button" value="Poke" id="poke" />
  </p>
  <script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
  <script src="/socket.io/socket.io.js"></script>
  <script>
  var socket = io.connect('http://localhost:8080');
  
  var username = prompt('What is your name?');
  socket.emit('newbie', username);
  
  socket.on('message', function(message) {
    alert('The server says: ' + message);
  });
    
  </script>
</body>
</html>

identification-user-socket-io-001

identification-user-socket-io-002

Notice that socket.io create a new session variable for every new connection, check the snippets below:

// server
socket.on('newbie', function(username) {
    socket.username = username; // store the userID here as session variable
	console.log('Username: ' + socket.username + ' connected!');
	socket.emit('message', 'You are connected as ' + socket.username);
  });

// client
var username = prompt('What is your name?');
  socket.emit('newbie', username); // YOU CAN SEND THE USER ID HERE socket.myvariable = myvariable;
  
  socket.on('message', function(message) {
    alert('The server says: ' + message);
  });

Now it is easy to create a simple chat software, the flow will be:

1. CLIENT
a.send e message to the server

socket.emit('your-event', { name: 'john', message: 'lorem' })

2. SERVER
a. get the name of the user and the message

socket.on('your-event', ({ name, message }) => {
    // name:
    // message:
})

b. broadcast the message with the name attached

socket.broadcast.emit('your-event', { name: 'john', message: 'lorem' })

3. CLIENT
a. receive the message broadcasted

socket.on('your-event', ({ name, message }) => {
    // name:
    // message:
})

b. render in the window the message
$(“your-tag”).append() [using JQuery]

Here the official tutorial about making a chat with socket.io: https://socket.io/get-started/chat/

Have fun!

For further informations:
– official web site of socket.io https://socket.io/
– other WebSockets for node.js https://blog.bitsrc.io/8-node-js-web-socket-libraries-for-2018-818e7e5b67cf
– using express https://www.programwitherik.com/getting-started-with-socket-io-node-js-and-express/
– using react https://itnext.io/building-a-node-js-websocket-chat-app-with-socket-io-and-react-473a0686d1e1
– ready to use commercial chat applications https://codecanyon.net/tags/socket.io

By |NodeJS, Web Design|Commenti disabilitati su node.js – websockets – socket.io

node.js – build a simple website

Hi! This tutorial is for beginners, to start learn node.js direct coding a simple website.
This stack is not the only stack available in the sea of stacks for node.js, consider this a starting point ok?

I assume you have just read my first three tutorials about node.js at:
a. [START WITH NODE.JS] http://www.lucedigitale.com/blog/lets-start-with-node-js/
b. [MODULES] http://www.lucedigitale.com/blog/node-js-modules-npm/
c. [PRODUCTION STACK WITH EXPRESS.JS AND EJS] http://www.lucedigitale.com/blog/node-js-project-structure-express-js-ejs-templates/

Then leggo!

1. Create a folder in your localhost environment, mine choice is Laragon:
laragon/www/mywebsite

2. Open Laragon’s terminal and go into laragon/www/mywebsite and type: node -v
If you see the node version it means that node.js is installed 😀

3. Type: npm install express-generator -g
-g stand for global, so you can access to this command from every folder

4. Type: npm install nodemon -g
-g stand for global, nodemon is a tool that helps develop node.js based applications.
Usually you have to stop and restart the server every time you change your js code, nodemon automatically restarting the node application when file changes in the directory are detected, great!

5. Type: express –view=ejs
Set the template system for express.js, this template system is ejs

6. Type: npm install
Install all dependencies

nodejs-web-folders

7. Type: nodemon start
If you see … [nodemon] starting `node ./bin/www start`… all gonna be all right :)

8. Open your browser at: http://localhost:3000
You will see the Express welcome message.
If you want switch the port you can do it at mywebsite/bin/www file here:

/**
 * Get port from environment and store in Express.
 */

var port = normalizePort(process.env.PORT || '3000');
app.set('port', port);

9. Open mywebsite/app.js file, check the row:

var index = require('./routes/index');

nodejs-routing-process

10. Jump to mywebsite/routes/index.js

Change the title of your home (http://localhost:3000) page as show below:

original code

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});

edited code

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', {page:'Home', menuId:'home'});
});

11. Then we need the HTML code inside the view, change mywebsite/views/index.ejs (notice is called by previous … res.render(‘index’,…)

<!DOCTYPE html>
<html lang="en">
<head>
 <% include partials/head %> 
</head>
<body>
<% include partials/menu %>
<div class="container-fluid bg-3 text-center">    
  <h3><%= page %></h3><br>
  <div class="row">
    <div class="col-sm-4">
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>
    </div>
    <div class="col-sm-4"> 
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>
    </div>
    <div class="col-sm-4"> 
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>
    </div>
  </div>
</div>
</body>
<% include partials/script %>
</html>

Notice the inclusion of separate elements of DOM:

<% include partials/head %>
<% include partials/menu %>
<% include partials/script %>

It is similar in PHP at:

<?php include 'head.php';?>

Let’s create the partials
a. mywebsite/views/partials/head.ejs

<title>Static Website | <%= page %></title>
<meta charset="utf-8">
<meta name="active-menu" content="<%= menuId %>">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="./stylesheets/style.css">

b. mywebsite/views/partials/menu.ejs

<nav class="navbar navbar-default">
  <div class="container">
    <div class="navbar-header">
      <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar">
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>                        
      </button>
      <a class="navbar-brand" href="#">LOGO</a>
    </div>
    <div class="collapse navbar-collapse" id="myNavbar">
      <ul class="nav navbar-nav navbar-right">
        <li id="home"><a href="/">HOME</a></li>
        <li id="about"><a href="/about">ABOUT US</a></li>
        <li id="contact"><a href="/contact">CONTACT US</a></li>
      </ul>
    </div>
  </div>
</nav>

c. mywebsite/views/partials/script.ejs

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="./javascripts/menu.js"></script>

nodejs-web-subfolders

d. Notice we have to create in mywebsite/public/javascript/menu.js

$(document).ready(function(){
    var element = $('meta[name="active-menu"]').attr('content');
    $('#' + element).addClass('active');
});

e. Notice we have to create this in mywebsite/public/stylesheets/style.css

.bg-3 { 
      background-color: #ffffff;
      color: #555555;
  }
  .container-fluid {
      padding-top: 70px;
      padding-bottom: 70px;
  }
  .navbar {
      padding-top: 15px;
      padding-bottom: 15px;
      border: 0;
      border-radius: 0;
      margin-bottom: 0;
      font-size: 12px;
      letter-spacing: 5px;
  }
  .navbar-nav  li a:hover {
      color: #1abc9c !important;
  }
.active>a {
    color: #1abc9c !important;;
  }

The final result (responsive):

nodejs-web-responsive

For further information about making website/apps with node.js:
– https://developer.mozilla.org/en-US/docs/Learn/Server-side/Express_Nodejs/skeleton_website
– https://codeforgeek.com/express-nodejs-tutorial/
– https://freshman.tech/learn-node/
– https://www.slant.co/topics/51/~best-javascript-templating-engines
– https://vuejs.org/
– https://levelup.gitconnected.com/simple-application-with-angular-6-node-js-express-2873304fff0f

Ref:
– https://medium.com/@bhanushali.mahesh3/creating-a-simple-website-with-node-js-express-and-ejs-view-engine-856382a4578

By |NodeJS, Web Design|Commenti disabilitati su node.js – build a simple website

node.js – project structure – express.js – ejs templates

This is a practical course using node.js and a localhost development environment.

INSTALL THE LOCAL ENVIRONMENT

For local development I use Laragon (https://laragon.org/), it is really well organized, easy to use and portable.

Download Laragon – Full, is has already the latest node.js stable edition inside, double click the Laragon icon and Start all services, if you are under Windows you will see a Windows Command Processor message, ignore it.

In the previous lessons we talked about:
– starting with node.js http://www.lucedigitale.com/blog/node-js-modules-npm/
– modules of node.js http://www.lucedigitale.com/blog/node-js-modules-npm/

Then we need to understand hoe to organize our project structure.
The simplest way (not the only way), is to install a ready ti use micro framework, the most popular microframework for node.js is express.js

1. Create the folder in laragon/www/myapp

2. Start the Laragon’s terminal and go inside laragon/www/myapp

3. Type: npm install express
This command will install the module express.js and all the dependencies inside the project myapp

4. Type: npm install -g express-generator
This command will install a useful module that will prepare the folder structure for you in just a second
With the option -g you can invoke the command from every folder

5. Type: express –view=ejs
If you see some message just type Y (yes)

6. Type: npm install
This install all dependencies

7. Type: npm start
This install all dependencies

8. Open the browser at localhost:3000
You will see the welcome message of express.js

9. Go inside laragon/www/myapp, here you can find the folder tree. This project structure is suitable for the template engine EJS (Embedded Javascript Templating – https://ejs.co/)

nodejs-folder-myapp

nodejs-folder-public

nodejs-folder-routes

nodejs-folder-view

Here some interesting folders:
– myapp is the root folder, inside here we will put all codes, images and other stuffs
– myapp/public with frontend images javascripts stylesheets
– myapp/view here the templates .ejs, try open index.ejs

<!DOCTYPE html>
<html>
  <head>
    <title><%= title %></title>
    <link rel='stylesheet' href='/stylesheets/style.css' />
  </head>
  <body>
    <h1><%= title %></h1>
    <p>Welcome to <%= title %></p>
  </body>
</html>

Notice the similarity betwenn:

<p>Welcome to <%= title %></p>
<p>Welcome to <?php echo $title; ?></p>

– myapp/routes here the controlles, try open index.js

var express = require('express');
var router = express.Router();

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});

module.exports = router;

Notice how the variable is passed to the view:

{ title: 'Express' }

EXPRESS ROUTING

With express.js routing operations will be easier

10. Type in terminal: CTRL+C
This will stop the current server, we do not need it at the moment

11. Create in laragon/www/myapp/routing.js
This is a brandnew app to test express.js routing system, you can call as you want even johndoeapp.js if you want 😀

Write the code inside:

var express = require('express');
var app = express();

app.get('/', function(req, res) {
  res.setHeader('Content-Type', 'text/plain');
  res.end('This is the homepage');
});

app.get('/guest', function(req, res) {
  res.setHeader('Content-Type', 'text/plain');
  res.end('This is guest page');
});

app.get('/users/:userid/user', function(req, res) {
  res.setHeader('Content-Type', 'text/plain');
  res.end('You are userid: ' + req.params.userid);
});

app.use(function(req, res, next){
  res.setHeader('Content-Type', 'text/plain');
  res.send(404, '404 - Page not exist!');
});

app.listen(8080);

12. Type in terminal: node routing.js
This will run our webserver at port 8080

13. type in the browser
http://localhost:8080
http://localhost:8080/guest
http://localhost:8080/users/15/user

The render will be:
This is the homepage
This is guest page
You are userid: 15

Notice the code that parse the variable and it is similar of GET call users.php?userid=15
This is a dynamic routing with express.js

app.get('/users/:userid/user', function(req, res) {
  res.setHeader('Content-Type', 'text/plain');
  res.end('You are userid: ' + req.params.userid);
});

For further information about project structure:
Ref: https://softwareontheroad.com/ideal-nodejs-project-structure/
Ref: https://rollout.io/blog/advanced-node-js-project-structure-tutorial/

By |NodeJS, Web Design|Commenti disabilitati su node.js – project structure – express.js – ejs templates

node.js – modules – NPM

This is a practical course using node.js and a localhost development environment.

INSTALL THE LOCAL ENVIRONMENT

For local development I use Laragon (https://laragon.org/), it is really well organized, easy to use and portable.

Download Laragon – Full, is has already the latest node.js stable edition inside, double click the Laragon icon and Start all services, if you are under Windows you will see a Windows Command Processor message, ignore it.

WHAT IS NODE JS MODULES AND NPM

Node.js is organized in modules, a module is like a javascript library that do something.
The core of Node.js has only few modolus (built-in module), to do foundamental operations like:
– HTTP transfer data
– File System management
– URL parsing
– Event fire and listen
etc…

If you need more you have to install other modules, for example to upload files, send emails, connect to a database. To live happy you have to use NPN (Node Package Manager https://www.npmjs.com/) that is the official ‘repository’ for Node.js modules, NPM works great because it install all dependencies too 😀

USE OF NPM – TEST INSTALLATION

1. Start Laragon (or your local environment), and run all services

2. Create a folder inside laragon/www/myapp

3. Start the terminal in Laragon ‘Cmder’, put the terminal inside myapp folder you will see in the command prompt: laragon\www\myapp then you are inside the right folder

4. type: npm -h
If you see the help instructions of npm it means that npm is installed and runs correctly, nice!

USE OF NPM – SEARCH MODULES

5. type: npm search mysql
You will see all the list of modules to manage mysql, it is clear, the syntax is npm search [keyword]

USE OF NPM – INSTALL MODULES

6. type: npm istall mysql
Go inside laragon/www/myapp npm has created:

a. folder ‘node_modules’ and inside it you can find mysql module and all dependencies.
NOTICE: the module is installed ONLY in the local folder of your app, if you have another app you have to install again for every app you create.

b. package-lock.json that contains the informations about downloaded modules

USE OF NPM – CODE WITH MODULES

7.

// load modules in code
var mysql = require('mysql'); 

// use modules functions
var con = mysql.createConnection({
  host: "localhost",
  user: "yourusername",
  password: "yourpassword"
});

con.connect(function(err) {
  if (err) throw err;
  console.log("Connected!");
});

nodejs

USE OF NPM – UPDATE MODULES

Super easy! Type: npm update
NOTICE: this command delete the old module and install the new one, pay attention to compatibility between old and new packages

USE OF NPM – PUBLIC YOUR MODULES

You can publish for free your own modules and become famous :) give a look to https://docs.npmjs.com/cli/publish

By |JavaScript, NodeJS, Web Design|Commenti disabilitati su node.js – modules – NPM

Let’s start with node.js

This is a practical course using node.js anda localhost development environment.

With node.js you can use js syntax to drive a server backend.

Under you can see the difference between node.js and PHP, PHP is multithread, node.js may be monothread, but it is flexible because of events.

nodejs-monothread

php-multithead

For local development I use Laragon (https://laragon.org/), it is really well organized, easy to use and portable, there are alternative, you can try Bitnami (https://bitnami.com/) or if you are skilled Docker (https://www.docker.com/), this time I’ll proceed with Laragon.

Download Laragon – Full, is has already the latest node.js stabe edition inside, double click the Laragon icon and Start all services
If you are under Windows you will see a Windows Command Processor message, ignore it.

1. Create a new folder inside laragon/www directory, my folder is nodejs
2. Then go inside laragon/www/nodejs and create the file server.js

var http = require('http');

var server = http.createServer(function(req, res) {
res.writeHead(200, {"Content-Type": "text/html"});
res.write('<!DOCTYPE html>'+
'<html>'+
' <head>'+
' <meta charset="utf-8" />'+
' <title>My Node.js page!</title>'+
' </head>'+ 
' <body>'+
' <p>Here is a paragraph of <strong>HTML</strong>!</p>'+
' </body>'+
'</html>');
res.end();
});
server.listen(8080);

With node.js you need to initialize a server, follow me now:

Load the module using require(‘http’); and create a server using the module http.createServer, a module is the same as JavaScript libraries

var http = require('http');
http.createServer(function(req, res)...

The page in the server in a ime type html (https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types)

res.writeHead(200, {"Content-Type": "text/html"});

Write the content of the page

res.write('<!DOCTYPE html>'+
'<html>'+...

You set the server at port 8080, you can assign any number you want (https://en.wikipedia.org/wiki/Port_(computer_networking))

server.listen(8080);

3. Run the Laragon terminal console INSIDE laragon/www/nodejs and type:
node server.js
The console doesn’t display anything and doesn’t respond – that’s totally normal, we are just started the server

4. Open your browser and go to the address http://localhost:8080.
This connect your own machine to the 8080 port on which the Node.js program is running.
In the browser you will se the render of an html page 😀

5. Change the code of server.js

' <p>Here is a paragraph of <strong>HTML</strong>! I have just changed this code</p>'+

6. Run the Laragon terminal console INSIDE laragon/www/nodejs and type:
a. CTRL+C this will stop the server
b. node server.js restart the server to get the changes

7. Reload http://localhost:8080 to render in the page the changes

8. Change the code of node.js

var http = require('http');
var url = require('url');

var server = http.createServer(function(req, res) {
var page = url.parse(req.url).pathname;
console.log(page);
res.writeHead(200, {"Content-Type": "text/plain"});
if (page == '/') {
res.write('You\'re in the home page');
}
else if (page == '/pageone') {
res.write('You\'re in page one!');
}
else if (page == '/pageone/subpageone') {
res.write('Hey, this is a subpage of pageone');
}
res.end();
});
server.listen(8080);

I will explain:

a. Get the url from the browser var url…
b. Parse the url var page…
c. if page==… write different code

...
var url = require('url');
...
var page = url.parse(req.url).pathname;

Stop e restart the server, type in the browser:
http://localhost:8080
http://localhost:8080/pageone
http://localhost:8080/pageone/subpage

9. Change the code another time:

var http = require('http');
var url = require('url');
var querystring = require('querystring');

var server = http.createServer(function(req, res) {
var page = url.parse(req.url).pathname;
var params = querystring.parse(url.parse(req.url).query);
console.log(page);
res.writeHead(200, {"Content-Type": "text/plain"});
	// parse query ################################################################
    if ('firstname' in params && 'lastname' in params) {
        res.write('Your name is ' + params['firstname'] + ' ' + params['lastname'] + '\r\n');
    }
    else {
        res.write('You do not have name AND surname' + '\r\n');
    }
	// parse url ##################################################################
	if (page == '/') {
		res.write('You\'re in the home page');
	}
	else if (page == '/pageone') {
		res.write('You\'re in page one!');
	}
	else if (page == '/pageone/subpageone') {
		res.write('Hey, this is a subpage of pageone');
	}
res.end();
});
server.listen(8080);

Stop and restart the server and in the browser type http://localhost:8080?firstname=John&lastname=Doe to see the result:

Your name is John Doe
You’re in the home page

Stop and restart the server and in the browser type http://localhost:8080?firstname=John&lastname=Doe to see the result:

You do not have name AND surname
You’re in the home page

10. Now I’ll create my own personal module, then go inside laragon/www/nodejs and create the file dtmodule.js

// Use the exports keyword to make properties and methods available outside the module file
exports.myDateTime = function () {
  return Date();
}; 

Change server.js

var http = require('http');
var url = require('url');
var querystring = require('querystring');

var dtmodule = require('./dtmodule.js'); // require my personal module
// Notice that we use ./ to locate the module, that means that the module is located in the same folder as server.js

var server = http.createServer(function(req, res) {
var page = url.parse(req.url).pathname;
var params = querystring.parse(url.parse(req.url).query);
console.log(page);
res.writeHead(200, {"Content-Type": "text/plain"});
	// parse query ################################################################
    if ('firstname' in params && 'lastname' in params) {
        res.write('Your name is ' + params['firstname'] + ' ' + params['lastname'] + '\r\n');
    }
    else {
        res.write('You do not have name AND surname' + '\r\n');
    }
	// parse url ##################################################################
	if (page == '/') {
		res.write('You\'re in the home page');
	        res.write("\r\nThe date and time are currently: " + dtmodule.myDateTime());
	}
	else if (page == '/pageone') {
		res.write('You\'re in page one!');
	}
	else if (page == '/pageone/subpageone') {
		res.write('Hey, this is a subpage of pageone');
	}
res.end();
});
server.listen(8080);

a. Load my own personal module var dtmodule = require(‘./dtmodule.js’);
b. Use the function inside res.write(“\r\nThe date and time are currently: ” + dtmodule.myDateTime());

Stop and restart the server and you will see at http://localhost:8080/

You do not have name AND surname
You’re in the home page
The date and time are currently: Tue Mar 31 2020 13:13:58 GMT+0200 (GMT+02:00)

By |NodeJS|Commenti disabilitati su Let’s start with node.js