Examples for Node.js 00-05

Zápisník experimentátora

Hierarchy: Node.js

These are commented examples for Node.js. You can find the source codes at https://github.com/RoboUlbricht/Node.js-tests. In this first bundle, you will find the simplest, what you can do. Examples are used to familiarize yourself with the program.

00-hello-world

Type text on console. After running the program, the Hello World! text appears on the console. The text on the console is used for applications at the command line. Using the listings, you will see what your program has done.

Install and run.

node hello.js

The source code has only two rows. The first line will force the use of variables in strict mode. This means you can not mistakenly define a variable with a typo in the name and then wonder why it does not work. At the same time, it's the way to force javascript interpreter to optimize performance. Get used to this always on the first line of the program, saving you time to miss unnecessarily lost hours in search of errors. The second row writes text on the command line console.

"use strict";
console.log("Hello World!");

01-hello-world-http

Writing text to the browser window. The port is 3000. For example, type http://127.0.0.1:3000/ into your browser. This is the simplest possible server. He will respond equally to each request. In this form, it may be meaningless, but the HTTP server is the basis for a huge number of applications on the Internet. In later examples, you will find an HTTP server that is created using the express package.

Install and run.

npm install
node index.js

The row with the function require shows how packages are added to your code. The row with the function createServer creates the HTTP server itself on port 3000. As a function parameter, there is another function that will execute code that responds to requests. The javascript development for Node.js uses this concept. Almost everywhere you will use such callback features. The last row is already known writing on the command line console.

"use strict";

var http = require("http");

http.createServer(function (request, response) {

   // Send the HTTP header
   // HTTP Status: 200 : OK
   // Content Type: text/plain
   response.writeHead(200, {'Content-Type': 'text/plain'});
  
   // Send the response body as "Hello World"
   response.end('Hello World\n');
}).listen(3000);

// Console will print the message
console.log('Server running at http://127.0.0.1:3000/');

02-hello-world-express

Writing text to the browser window. The port is 3000. For example, type http://127.0.0.1:3000 to your browser. This HTTP server is created using the express package. This is a popular package for such purposes. Against the simple HTTP server at first sight are almost no changes. This is true only for simple servers. As soon as your project starts to grow and you will bring a larger number of different pages into your browser, it will still be easy and straightforward to do it with express.

Install and run.

npm install
node hello.js

The row with the require function adds the express package. The row with the get function shows how GET requests are processed. If you would need to add more pages, then you will add the addresses and the server will do the rest.

'use strict';

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

app.get('/', function (req, res) {
  res.send('Hello World!\n')
})

var server = app.listen(3000, function () {
  var host = server.address().address;
  var port = server.address().port;

  console.log('Example app listening at http://%s:%s', host, port);
})

03-express-static

Writing text to the browser window. The port is 3000. For example, type http://127.0.0.1:3000/static/abc.txt into your browser. In this example, I've extended the previous example with static pages. You will be able to add a lot of pages to your browser, for example, as you will have cascading styles, pictures and javascripts to be used in the browser window. All of this is a static site and there is no reason to have to program something about sending them. Express will send it for you.

Install and run.

npm install
node static.js

A previous example is changed only in a single line. A row with the use function says that all addresses /static/something are to be delivered from your local public directory.

'use strict';

var express = require('express')
var app = express()
var path = require("path")

app.use('/static', express.static(path.join(__dirname, 'public')))

app.get('/', function (req, res) {
  res.send('Hello World!\n')
})

var server = app.listen(3000, function () {
  var host = server.address().address;
  var port = server.address().port;

  console.log('Example app listening at http://%s:%s', host, port);
})

04-express-base

HTTP server that returns an HTML page response. The port is 3000. For example, type​ http://127.0.0.1:3000/ into your browser. I have generated this example using the Express Generator. In order to be used, you need to install the package globally using the npm install -g express-generator command. Then I generated the application with express --view=pug 04-express-base. It generates quite a lot of files that make up the skeleton of the application. You can store static files in your public directory. In the routes directory, you are given javascript processing of individual page requirements. Add templates to each page in the views directory. In this case, these are PUG templates.

Install and run.

npm install
npm start

Two files have been created to run your app. The first is ./bin/www, which is the creation of the HTTP server using express. The second is ./app.js where your app is set up. For us, there are essential rows with the require functions that are directed to the ./routes directory.

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

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

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', index);
app.use('/users', users);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;

For example, page /users is created in the ./routes/users.js file.

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

/* GET users listing. */
router.get('/', function(req, res, next) {
  res.render('users', {
   title: 'Express Arduino Slovakia Users',
   users: ['Milan', 'Peter', 'Erik']
  });
});

module.exports = router;

And that's what the PUG template looks like in the ./views/users.pug file.

extends layout

block content
  h1= title
  p Zoznam užívateľov.
  ul
    each val in users
      li= val

05-express-json

HTTP server returning JSON. The port is 3000. For example, type http://127.0.0.1:3000/ into your browser. The last example I created was the same as the previous one. I just added a JSON page to it, because I will be doing a lot of these pages in other examples.

Install and run.

npm install
npm start

Example processing request in ./routes/json.js.

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

/* GET home page. */
router.get('/', function(req, res, next) {
  res.json({ title: 'Arduino Slovakia JSON', hodnota: 25 });
});

module.exports = router;

09.07.2017


Menu