Обзор фреймворков для создания серверного приложения на nodejs

Что такое Node.js?

Node или Node.js — серверная реализация языка программирования JavaScript, основанная на движке V8. Предназначена для создания масштабируемых распределённых сетевых приложений, таких как веб-сервер. Node.js по целям использования сходен с каркасами Twisted на языке Python и EventMachine на Ruby. В отличие от большинства программ JavaScript, этот каркас исполняется не в браузере клиента, а на стороне сервера.

Что такое framework?

framework — это набор инструментов, библиотек, хорошего кода, который поможет превратить рутинные задачи в модули, которые можно использовать неоднократно. Задача framework’а — позволить дизайнеру или разработчику сфокусироваться на задачах, являющимися уникальными в рамках данного проекта. Иначе говоря, не изобретать колесо раз за разом.

Теперь непосредственно сами framework’и

Рассмотрим такие вспомогательные средства для серверной разработки на JS, как:

  • Express
  • Meteor
  • Mean
  • Koa
  • Hapi
  • Sails
  • Socket

Express

Express — это минималистичный и гибкий веб-фреймворк для приложений Node.js, предоставляющий обширный набор функций для мобильных и веб-приложений.

Express, как хорошо известно, развивается своим путём, в отличие от других фреймворков, во многом опирающихся на Rails, но также много позаимствовал из другого Ruby-фреймворка под названием Sinatra. Концепция простая: фреймворк предоставляет достаточно возможностей для запуска и работы «на лету», не требуя много времени на подготовку.

Это фреймворк, делающий создание большинства сайтов очень простым. Первое, что вам нужно будет сделать — установить его.
$ npm install express --save
Вместе с командой node у вас появится команда npm. Этот инструмент даёт вам доступ к колоссальному количеству модулей, созданных сообществом, и Express как раз один из них.

Плюсы данного framework’а:

1)Низкий порог вхождения, Express — это практически стандарт Node.js-приложения.
2)Полная кастомизация.

Минусы:

1)Все ресурсы необходимо создавать вручную и, в результате, появится много повторного кода или хуже — собственная библиотека.
2)Каждый ресурс требует тестирования или простой проверки на 500-ую ошибку.
3)Рефакторинг станет болезненным, так как будет необходимо править всё и везде.
4)Нету стандартного подхода, нужно искать свой.
->Пример разработки на Express
->Официальный сайт

Meteor

Meteor является MVC (Model-View-Controller) фреймворком с открытым исходным кодом, с помощью которого вы можете создавать Web-приложения реального времени. Одна из важнейших особенностей платформы состоит в том, что она позволяет использовать один и тот же код как на стороне сервера, так и на стороне клиента. Между сервером и клиентом, как правило, передаются данные, а не HTML-код. Фреймворк поддерживает OS X, Windows и Linux. Его реактивная модель программирования позволяет создавать приложения используя меньше JavaScript кода.

Плюсы данного framework’а:

1)Код сервера и клиента пишется на одном языке
2)Удобно отлаживать код прямо из браузера
3)Можно быстро продемонстрировать состояние проекта клиенту при помощи meteor deploy

Минусы:

1)Не годится для крупных проектов
2)Совершенно не годится для мобильных устройств из-за большого количества JavaScript
3)В коде некоторые тривиальные задачи приходится решать при помощи громоздких конструкций
->Пример разработки на Meteor
->Официальный сайт

Mean

MEAN (аббревиатура от MongoDB, Express.js, Angular.js, Node.js) — набор (комплекс) серверного программного обеспечения, который используется для веб-разработки. На уровне клиента, сервера и базы данных весь стек MEAN написан на JavaScript. Смещение базовой платформы с ОС (Linux) к среде исполнения JavaScript (Node.js) несет с собой независимость от ОС: Node.js работает на Windows и OS X так же, как и на Linux.

Главный сдвиг MEAN заключается в переходе от традиционного генерирования страниц на стороне сервера к ориентации на одностраничные приложения (SPA) на стороне клиента.
->пример разработки на Mean
->Официальный сайт

Koa

Команда разработчиков фреймворка Express.js создала еще один фреймворк под названием Koa.js — футуристический фреймворк следующего поколения для Node.js, который обещает быть более кратким и ярким, в сравнении с Express.js. Koa.js сфокусирован на создании веб приложений и API, его главное преимущество это генераторы, которые являются отличным способ избежать колбеков, а также помощь разработчикам в исправлении ошибок.
->Разработка приложения на koajs
->Официальный сайт

Hapi

Менее известный фреймворк, который разрабатывается командой Walmart Labs. В отличие от Express у него несколько другой подход, предоставляющий больший функционал сразу из коробки. К плюсам можно отнести полный контроль над приемом запросов и детальная справка с генерацией документации.

Плюсы данного framework’а:

1)Полный контроль над приёмом запросов.
2)Детальная справка с генерацией документации.

Минусы:

1)hapi, также как Express, даёт отличные возможности, но как их использовать, вы должны понять сами.
->Официальный сайт

Sails

Sails.js — это MVC (Model-View-Controller) фреймворк, который позволяет легко и быстро создавать Node.js приложения. Sails.js лучше всего подходит для создания реалтаймовых приложений. Он разработан на основе шаблона MVC, как Ruby On Rails, но также поддерживает требования современных приложений: программные интерфейсы с масштабируемой, сервисно-ориентированной архитектурой. Этот фреймворк особенно хорошо подходит для разработки чатов, инструментальных панелей реального времени и многопользовательских игр.
->Официальный сайт

Socket

Socket. IO — JavaScript библиотека для веб-приложений и обмена данными в реальном времени. Состоит из двух частей: клиентской, которая запускается в браузере и серверной для node.js. Оба компонента имеют похожее API.

Плюсы:

1)Мощный и простой в использовании
2)Используется многими крупными компаниями
->Официальный сайт
->Использование библиотеки Socket
->Еще один пример

Заключение

Собственно, на этом мы расмотрели несколько framework’ов для серверной разработки на JS. Для более детального погружения необходимо воспользоваться ссылками на официальные сайты.

Instruction for creating a server app on Nodejs, Express and MongoDB


Based on simple example of app in which we can create, read, update and delete simple text documents

Component installation

The official site of nodejs (https://nodejs.org/) has detailed installation instructions

For centos:

1
2
3
$ curl —silent —location https://rpm.nodesource.com/setup_9.x | sudo bash -
$ sudo yum -y install nodejs
$ sudo yum install gcc-c++ make

For Ubuntu:

1
2
3
$ curl -sL https://deb.nodesource.com/setup_9.x | sudo -E bash -
$ sudo apt-get install -y nodejs
$ sudo apt-get install -y build-essential

Organize a folder for the project and execute a command for project initialization in it:

1
$ npm init

Answer the following questions

  • Project name
  • Project version
  • Description
  • Entry point
  • Testing team
  • Githhab’s repository
  • Project keywords
  • Author
  • License
Confirm and you’ll see file package.json, describing the project.

Now install the remaining components: Express and MongoDB (the latest version of the plugin does not work correctly with the database, so it’s better to install an earlier one):

1
$ npm install --save express mongodb@2.2.16

Also, for the convenience of handling url-encoded requests, install the body-parser:

1
$ npm install --save body-parser

And for the convenience of development, it is better to install Nodemon, which will restart the server every time when any files change:

1
$ npm install --save-dev nodemon

To attach Nodemon, you need to add the following to package.json:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
{
"name": "notable",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error^ no test specified\" && exit 1",
"dev": "nodemon server.js"
},
"author": "",
"license": "ISC",
"dependencies": {
"body-parser": "^1.18.2",
"express": "^4.16.2",
"mongodb": "^2.2.16"
},
"devDependencies": {
"nodemon": "^1.14.2"
}
}

To be able to test app install Postman(https://www.getpostman.com/), which will simulate requests

Starting the server

Create file server.js in root directory, in which we write dependencies, specify the port and start listening:

1
2
3
4
5
6
7
8
const express        = require('express');
const MongoClient = require('mongodb').MongoClient;
const bodyParser = require('body-parser');
const app = express();
const port = 8080;
app.listen(port, () => {
console.log('We are live on ' + port);
});

Run the server:

1
npm run dev

In the terminal you can now see the message “We are live on port 8080”

Structure of project

For more convenient structuring of the project it is necessary to create an ‘app’ folder, in it we create the ‘routes’ folder, and in it - files ‘index.js’ and ‘note_routes.js’

So, the structure looks like this: in app/ routes - our route handlers, in the node_modules folder - the modules of our project, and server.js directly describes our server.

Connecting the DB

Add the ‘config’ directory to the project root, create a ‘db.js’. file in it.
In the file db.js write the following:

1
2
3
module.exports = {
url : 'mongodb://localhost:27017/<yourDataBase>'
};

In the file ‘server.js’ we add:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
const express        = require('express');
const MongoClient = require('mongodb').MongoClient;
const bodyParser = require('body-parser');
const db = require(‘./config/db’);
const app = express();
const port = 8080;
app.use(bodyParser.urlencoded({ extended: true }));
MongoClient.connect(db.url, (err, database) => {
if (err) return console.log(err)
require(‘./app/routes’)(app, database);
app.listen(port, () => {
console.log('We are live on ' + port);
});
});

Creating a text document

In app/routes/note_routes.js we write:

1
module.exports = function(app, db) { };

In app/routes/index.js:

1
2
3
4
5
6
7
8
9
10
11
12
13
const noteRoutes = require('./note_routes');
module.exports = function(app, db) {
app.post('/notes', (req, res) => {
const note = { text: req.body.body, title: req.body.title };
db.collection('notes').insert(note, (err, result) => {
if (err) {
res.send({ 'error': 'An error has occurred' });
} else {
res.send(result.ops[0]);
}
});
});
};

Reading a text document

By analogy with app.post, we write another method:

1
2
3
4
5
6
7
8
9
10
11
app.get('/notes/:id', (req, res) => {
const id = req.params.id;
const details = { '_id': new ObjectID(id) };
db.collection('notes').findOne(details, (err, item) => {
if (err) {
res.send({'error':'An error has occurred'});
} else {
res.send(item);
}
});
});

Deleting of text document

By analogy with app.post, we write another method:

1
2
3
4
5
6
7
8
9
10
11
app.delete('/notes/:id', (req, res) => {
const id = req.params.id;
const details = { '_id': new ObjectID(id) };
db.collection('notes').remove(details, (err, item) => {
if (err) {
res.send({'error':'An error has occurred'});
} else {
res.send('Note ' + id + ' deleted!');
}
});
});

Updating of text document

By analogy with app.post, we write another method:

1
2
3
4
5
6
7
8
9
10
11
12
app.put ('/notes/:id', (req, res) => {
const id = req.params.id;
const details = { '_id': new ObjectID(id) };
const note = { text: req.body.body, title: req.body.title };
db.collection('notes').update(details, note, (err, result) => {
if (err) {
res.send({'error':'An error has occurred'});
} else {
res.send(note);
}
});
});

Testing with Postman

Postman allows specify the type of request (get, post, put, update), it’s address and port and add various parameters to the request body, for example, an empty POST request on the 8080 port.
Upon execution of the request, we see the server response.

alt-текст
Example of a POST request with a filled body:

alt-текст
Let the server print the request to the server console, then we’ll see:

alt-текст

Node installing
https://nodejs.org/en/download/package-manager/#enterprise-linux-and-fedora
Postman installing
https://www.getpostman.com/
Similar articles

  1. https://medium.freecodecamp.com/building-a-simple-node-js-api-in-under-30-minutes-a07ea9e390d2#.eybmlr1g9
  2. https://habrahabr.ru/company/ruvds/blog/321104/
  3. https://loftblog.ru/material/4-podklyuchenie-bazy-dannyx-k-express/
  4. http://coenraets.org/blog/2012/10/creating-a-rest-api-using-node-js-express-and-mongodb/

Instructions for creating a server application on nodejs + express

Attention

If you don’t have knowledge of JavaScript, you need to do something about it. For example, read the online tutorial: https://learn.javascript.ru/

Node.js what is it?

Node.js is a JavaScript runtime built on Chrome’s V8 JavaScript engine. Node.js uses an event-driven, non-blocking I/O model that makes it light and efficient. Node.js’ package ecosystem, npm, is the largest ecosystem of open source libraries in the world.

Installation

Go to the official site https://nodejs.org/en/ to download it. On the main page we see two possible options for download: the latest version of NodeJS and the LTS version.

Download, install. There you can find instructions for setting up:

centos:

1
2
3
curl —silent —location https://rpm.nodesource.com/setup_9.x | sudo bash - 
sudo yum -y install nodejs
sudo yum install gcc-c++ make

ubuntu:

1
2
3
curl -sL https://deb.nodesource.com/setup_9.x | sudo -E bash - 
sudo apt-get install -y nodejs
sudo apt-get install -y build-essential

You can verify the installation by:

1
node --version

The command will show the current version of the program.

REPL

After installing NodeJS, we get a tool like REPL available to us. REPL (Read Event Printed Loop) represents the ability to run expressions in the JavaScript language on the command line or terminal.

So, run the command line (on Windows) or the terminal (on OS X or Linux) and enter the node command. After entering this command, we can execute various expressions in JavaScript.

Packages in Node.js

In short, a package in Node.js is one or more JavaScript files that represent a library or tool.

npm (node manager) is a standard package manager that automatically installs with Node.js. It is used to download packages from the npm cloud server, or to download packages to these servers.

Now, where to begin?

Create a project directory. Then open the terminal, and execute the command:

1
npm init

After answering the questions the file ‘package.json’ will be in the project directory

Express

Express is a minimalistic and flexible web framework for Node.js applications built on the connect framework.

Main purpose is routing and intermediate processing with minimal own functionality: Express application, in fact, is a series of operations of intermediate processing functions (middleware).

To set up the Express in the terminal from the project directory, execute the command:

1
npm install express

How to apply this

Create a file server.js.

To use the Express framework, you need to connect the express module, and create the application.

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

Run the application using the command:

1
2
3
app.listen(8080, function(){
console.log('server start on port 8080');
})

As a result, the server will start, but if you execute a query to application localhost: 8080, you get the error:
`Cannot GET /`
This is because there is no route in the program.

Routing

Routing determines how the application responds to a client request to a specific address, and to a specific HTTP request method.

Each route can have several handlers.

the following structure used to determine the route:

1
app.METHOD(path, handler)

app - the instance of the express application
METHOD - HTTP request method
path - the path to the server
handler - the function-handler

We continue to apply

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
var express = require('express');
var app = express();

// We call the get method, it will set up a handler that will respond to get requests, for the route '/'
app.get('/', function(request, response){
console.log(request.url);
response.send('<h1>Hello, world!</h1>');
});

// Same for the '/ about' route
app.get('/about', function(request, response){
console.log(request.url);
response.send('<h1>About Page</h1>');
});
app.listen(8080);

What else?

Middleware-function

Middleware-functions are functions that have access to the request object req, the response object res, and to the next intermediate processing function in the “request-response” loop of the application next.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
var express = require('express');
var app = express();

app.use('/', function(request, response, next){
console.log('Prehandler...');
// pass control to the next handler
next();
});

app.get('/', function(request, response){
console.log('Main handler');
// complete the response from the server
response.end();
});

app.listen(8080);

Thus, both functions are executed when accessing the root path.

Routing

Using the express.Router class, you can create modular, mounted route handlers. An instance of this class represents a complex system of intermediate handlers and routing.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
var express = require('express');
var app = express();

var router = express.Router();

router.route("/")
.get(function(req, res){
res.send("List of products. Get method.");
})
.post(function(req, res){
res.send("Product created. POST method.");
});
router.route("/:id")
.get(function(req, res){

res.send(`Product ${req.params.id}`);
});

app.use("/products", router);

app.get("/", function(req, res){
res.send("Main page");
});

app.listen(8080);

When executing the localhost:8080/products query, the route will be determined from the router. The corresponding handler function will be executed.

Finish

In the manual, you learned about node.js+express. This will be enough for a quick start.
For more information refer to sources.

Sources:

node:
https://nodejs.org/en/
https://itvdn.com/ru/video/node_js/express - not free resource unfortunately, but useful.
https://learn.javascript.ru/screencast/nodejs - alternative

npm:
https://www.npmjs.com/

express:
http://expressjs.com/ru/
https://nodeguide.ru/doc/modules-you-should-know/express/
http://expressjs.com/ru/4x/api.html - express api directory

Creating simple aplication using Node.js, Express and PostgreSQL.

Installation Node.js

Windows:

In order to start, go to the download page Node.js (https://nodejs.org/en/download/). Select the installer that you want to download and install.

After we run the installer and complete the installation step-by-step.

CentOS:

To install Node.js, you need to connect to the server using the SSH protocol. After that, you need to install the latest version of .nodejs from the repositories. For this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
$ yum update

// Install the Development Tools group
$ yum -y groupinstall "Development Tools"

// Enter the command to connect to the server and create several concurrent sessions
$ yum -y install screen

// Go to /usr/src and load the archive with Node.js
$ cd / usr / src
$ wget http://nodejs.org/dist/v0.10.4/node-v0.10.4.tar.gz

// Extract the files from the archive and put them in the directory
$ tar zxf node-v0.10.4.tar.gz
$ cd node-v0.10.4

// Create the installation file and run it
$ make
$ make install

Node.js is installed. By default, its binary code is in /usr/local/bin/node.

Ubuntu

To install Node and npm via apt-get, run these commands:

1
2
3
4
sudo apt-get update  
sudo apt-get install nodejs
sudo ln -s /usr/bin/nodejs /usr/bin/node
sudo apt-get install npm

If you still want to use apt-get, but need a much newer version of Node, you should use this method.

This is very similar to the last one I showed you, but instead we’ll be running a script (maintained and distributed by NodeSource) to show the package manager where to get the latest version.

1
2
3
4
5
6
7
8

curl -sL https://deb.nodesource.com/setup_5.x | sudo -E bash -
sudo apt-get install -y nodejs
sudo ln -s /usr/bin/nodejs /usr/bin/node

```

To verify that you have *Node.js* installed and check the version, run:

$ node –version

1
2

To start, run:

$ node

1
2
3
4
5


### Setting dependencies.

You can interactively generate the * package.json * file with the * npm init * command in the terminal.

$ npm init

1
2
3
4

After running the command you will be asked to enter some data. After you receive them * package.json * will be automatically generated and placed in the folder of your application.

If any dependencies are not installed, you can add them to your application with the following command:

npm install[module name] –save

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15


### PostgreSQL installing.

PostgreSQL is a very popular database server, so it is present in official Ubuntu repositories.

**Windows**

You can download PostgreSQL from the official site download page here - http://www.postgresql.org/download/windows/

Download the installer by selecting a version suitable for the system capacity and following the steps offered by the installer.

**CentOS**

To install the latest version, add the official repository with the following command:

$ sudo rpm -Uvh http://yum.postgresql.org/9.5/redhat/rhel-7-x86_64/pgdg-centos95-9.5-2.noarch.rpm

1
2
After the repository is added to your system, you can proceed to install the program.
The installation of Postgresql CentOS is performed by the command:

$ sudo yum install postgresql96-server postgresql96

1
2

Immediately after installing Postgresql, the server is not yet ready for use, you need to initialize the necessary databases. To do this, execute:

$ /usr/pgsql-9.6/bin/postgresql96-setup initdb

1
2
3
4
5
6
7


**Ubuntu**

However, in PPA developers PostgreSQL you can find the latest version.

Add the PostgreSQL repository to the system source list:

$ sudo sh -c ‘echo “deb http://apt.postgresql.org/pub/repos/apt/ lsb_release -cs-pgdg main” >> /etc/apt/sources.list.d/pgdg.list’

1
2

and a key:

$ wget -q https://www.postgresql.org/media/keys/ACCC4CF8.asc -O - | sudo apt-key add -

1
2

This will allow you to receive the most recent versions when upgrading packages.

initdb -U postgres -D data
pg_ctl -D data start
psql -U postgres

1
2
3
4
5

Here *postgres* is the user name, it's better to specify it by default, for starters, and *data* is the directory where databases will be stored, you can specify any convenient.
After that *pg_ctl* starts PostgreSQL (indicating the directory with the databases).

At the end, we should see a welcome console:

postgres=#

1
2
3
4

### Express installing.

To install Express and add it to the dependency list, you must go to the project folder and run the command:

$ npm install express –save

1
2
3
4

### Creating a simple server application.

Create the directory where your project will be stored.

$ mkdir nodejs-express-postgresql/
$ cd nodejs-express-postgresql/

1
2

Now we need to initialize our application:

$ npm init -y

1
2
3
4

This command will create * package.json * with standard configuration settings.

Now create a file with our application.

$ touch app.js

1
2

Now you need to connect and configure Express.

const express = require(‘express’);
const bodyParser = require(‘body-parser’);

// Set up the express app
const app = express();

// Setup a default catch-all route that sends back a welcome message in JSON format.
app.get(‘*’, (req, res) => res.status(200).send({
message: ‘Welcome, my frined.’,
}));

module.exports = app;

1
2

Now if we run our server

npm run start:dev

1
2
3
4
5
6
7

And go to http://localhost:8000/, then we will see the message *Welcome, my friend.*

Now you need to connect our database.
We will immediately use the pool, not separate connections. This is a common practice, especially for PostgreSQL. The pool allows you to store multiple connections, thus not wasting time creating them and not dealing with their management.

First, configure the dependency, then add the connection to our database.

const Pool = require(‘pg’).Pool;

1
2

By default, *PostgreSQL* does not have a password, and the standard port is 5432.

const config = {
user: ‘postgres’,
host: ‘localhost’,
database: ‘users’,
password: ‘’,

};

const pool = new Pool(config);

1
2

Now it only remains to make our function, which will show all entries from the table *users*.

(async () => {
const client = await pool.connect()
try {
const res = await pool.query(“select * from users”);
console.log(res.rows[0])
} finally {
client.release()
}
})().catch(e => console.log(e.stack))

```

Now when you reboot our server you can see the result.

PostgreSQL:
https://node-postgres.com/
http://expressjs.com/ru/guide/database-integration.html

Node.js:
https://nodejs.org/en/
https://medium.com/devschacht/node-hero-chapter-1-239f7afeb1d1
https://node-postgres.com/features/pooling

Express:
http://expressjs.com/ru/

NPM:
https://www.npmjs.com/

Simple application Node.js + Koa

Koa is a new web framework designed by the team behind Express, which aims to be a smaller, more expressive, and more robust foundation for web applications and APIs.
Through leveraging generators Koa allows you to ditch callbacks and greatly increase error-handling. Koa does not bundle any middleware within core, and provides an elegant suite of methods that make writing servers fast and enjoyable.

Let’s create a simple Koa application, and review some useful middlewares for it.

Requirements

Koa requires Node 7.6.0 or higher for async/await syntax.
You can use older Node versions with Babel (see more about it at Koa installation section).

Environment

Node.js

If Node is not installed yet, you can download it here. If you are a lucky owner of Linux or macOS, package managers can be used - this method described here.
To check that the Node installation is correct, you can run the command:

1
$ node --version

That will print the Node version.
Also for NPM:
Also don’t forget about NPM (Node Package Manager):

1
$ npm --version

You can use NVM (Node Version Manager) and if you know what it is, it shouldn’t be a problem.

Dependencies installation

Create directory where all the code will be located. Run terminal and open this directory.

Let’s initialize the package environment. This, at a minimum, will help us keep the list of dependencies with our code, and as a maximum - create a great package for distribution to the community.

1
$ npm init

NPM will ask you a few questions. Type answers for package name of author.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
$ npm init

This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sensible defaults.

See `npm help json` for definitive documentation on these fields
and exactly what they do.

Use `npm install <pkg>` afterwards to install a package and
save it as a dependency in the package.json file.

Press ^C at any time to quit.
package name: (ex) koa-simple-app
version: (1.0.0)
description: Koa simple application
entry point: (index.js)
test command:
git repository:
keywords:
author: Nariman Safiulin <woofilee@gmail.com>
license: (ISC)
About to write to <..>\package.json:

{
"name": "koa-simple-app",
"version": "1.0.0",
"description": "Koa simple application",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "Nariman Safiulin <woofilee@gmail.com>",
"license": "ISC"
}


Is this ok? (yes)

You should see the package.json file that NPM has created.

Install koa:

1
$ npm i koa

Hello, World!

Let’s create a file index.js, and copy-paste the next slightly modified version of standard Koa example.

1
2
3
4
5
6
7
8
9
10
11
const Koa = require('koa');

const app = new Koa();

app.use(async ctx => {
ctx.body = 'Hello, World!';
});

app.listen(3000, () => {
console.log('Server running on port 3000');
});

Code is simple to understand.
We’ve created a Koa application instance. With a use method you can add a middleware to the chain. All middlewares will be executed in sequence with each request. Each middleware accepts two arguments - ctx and next, where ctx is a request context (obviously), and next - the next middleware in the chain. In the last middleware the next argument can be omitted (as in example).
After that we’ve tell Koa to listen the port 3000. Callback allows us to understand that the server actually started, rather than hangs.

Now we can start the server:

1
$ node index.js

If the server has successfully started, open the browser and go to localhost:3000. You should see the Hello, World! page.

You can read more about Koa functionality on the Koa website.

Useful stuff

You can find alternatives for every middleware in the next list, as well as other middlewares.

Koa-router

The library allows you to get the necessary functionality of routing requests to different handlers. Without this middleware, it’s not very possible to do something more than Hello, World!.
In addition to koa-router, there are a lot of other analogues, for example, a simpler [koa-route] (https://github.com/koajs/route), which is difficult to come up with any application for ambitious purposes, and a router with data validation of incoming and outgoing data in requests/reponses [joi-router] (https://github.com/koajs/joi-router). Nevertheless, koa-router is the most popular at the moment, and it has balanced functionality, nothing superfluous.

1
$ npm i koa-router
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
const Koa = require('koa');
const Router = require('koa-router'); // Changed

const app = new Koa();
const router = new Router(); // Router initialization

router.get('/', (ctx, next) => { // We will handle GET requests
ctx.body = 'Hello, World!';
});

app.use(router.routes()).use(router.allowedMethods()); // Add routes to the middleware chain, and respond to the OPTIONS requests.

app.listen(3000, () => {
console.log('Server running on port 3000');
});

Read more about koa-router here.

Koa-bodyparser

Koa out of the box doesn’t know how to parse some data in requests.
If we need to accept requests with a JSON body, for example, then this middleware is necessary.

1
$ npm i koa-bodyparser
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
const Koa = require('koa');
const BodyParser = require('koa-bodyparser'); // Changed

const app = new Koa();

app.use(bodyParser()); // Use Parser before the route handler

app.use(async ctx => {
// Parsed data is located in ctx.request.body
// Empty object as a placeholer will be used if there is nothing to parse
ctx.body = ctx.request.body;
});

app.listen(3000, () => {
console.log('Server running on port 3000');
});

More about koa-bodyparser is here.

Koa-logger

Logs of what requested, and what responded, are also needed. For development, the koa-logger can be used.
It will look something like this (taken from the page of the package):

1
2
3
4
5
6
7
8
<-- GET /
--> GET / 200 835ms 746b
<-- GET /
--> GET / 200 960ms 1.9kb
<-- GET /users
--> GET /users 200 357ms 922b
<-- GET /users?page=2
--> GET /users?page=2 200 466ms 4.66kb

Very simple. If you want more information about requests, you can try [bunyan-logger] (https://github.com/koajs/bunyan-logger).

1
$ npm i koa-logger
1
2
3
4
5
6
7
8
9
10
11
12
13
14
const Koa = require('koa');
const Logger = require('koa-logger'); // Changed

const app = new Koa();

app.use(Logger()); // Logger is before the route handler

app.use(async ctx => {
ctx.body = 'Hello, World!';
});

app.listen(3000, () => {
console.log('Server running on port 3000');
});

Repository of koa-logger is located here.

@koa/cors

CORS requests sometimes are needed.

1
$ npm i @koa/cors@2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
const Koa = require('koa');
const CORS = require('@koa/cors'); // Changed

const app = new Koa();

app.use(CORS()); // Before the route handler!

app.use(async ctx => {
ctx.body = 'Hello, World!';
});

app.listen(3000, () => {
console.log('Server running on port 3000');
});

Repository of @koa/cors is here.

Koa-compress

Compress responses from the server.

1
$ npm i koa-compress
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
const Koa = require('koa');
const Compress = require('koa-compress'); // Changed

const app = new Koa();

app.use(Compress({
filter: function (content_type) {
return /text/i.test(content_type)
},
threshold: 2048,
flush: require('zlib').Z_SYNC_FLUSH
})); // Before the route handler! We'll compress any text responses.

app.use(async ctx => {
ctx.body = 'Hello, World!';
});

app.listen(3000, () => {
console.log('Server running on port 3000');
});

Read more about koa-compress here.

Koa-session

If cookie sessions are required, then this is a good package.

1
$ npm i koa-session
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
const Koa = require('koa');
const Session = require('koa-session'); // Changed

const app = new Koa();

app.keys = ['secret key']; // We need some random bytes to sign our cookie session

app.use(Session(app)); // All options by default

app.use(async ctx => {
// Let's count the number of Hello, World! page views.
// Don't forget about the fact, that the browser will ask a favicon, that's why the number can be increased by 2.
let n = ctx.session.views || 0;
ctx.session.views = ++n;
ctx.body = `Hello, World! x${n}`;
});

app.listen(3000, () => {
console.log('Server running on port 3000');
});

More koa-session options is here.

Koa-JWT

And JWT, of course. Very useful for API development. It’s a little difficult to come up with a simple example using this library, so you can read README in the package repository.

1
$ npm i koa-jwt

Read more about koa-jwt here.

In conclusion

Koa performs its only important function - to accept requests to the server, and apply a middleware chain to them. This allows you to achieve good flexibility in the development of the application, and to use only what is needed.
It’s also very similar to [Express] (https://expressjs.com/).
So there should not be any problems with it.

Simple application Node.js + Koa + MongoDB

Koa

From Koa introduction:

Koa is a new web framework designed by the team behind Express, which aims to be a smaller, more expressive, and more robust foundation for web applications and APIs. Through leveraging generators Koa allows you to ditch callbacks and greatly increase error-handling. Koa does not bundle any middleware within core, and provides an elegant suite of methods that make writing servers fast and enjoyable.

Requirements

Koa requires Node 7.6.0 or higher for async/await syntax.
You can use older Node versions with Babel (see more about it at Koa installation section).
MongoDB version does not matter. We will use the latest one.

Environment

Node.js

If Node is not installed yet, you can download it here. If you are a lucky owner of Linux or macOS, package managers can be used - this method described here.
To check that the Node installation is correct, you can run the command:

1
$ node --version

That will print the Node version.
Also for NPM:

1
$ npm --version

Dependencies installation

Create directory where all the code will be located. Run terminal and open this directory.

Let’s initialize the package environment:

1
$ npm init

NPM will ask you a few questions. Type answers for package name of author.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
$ npm init

This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sensible defaults.

See `npm help json` for definitive documentation on these fields
and exactly what they do.

Use `npm install <pkg>` afterwards to install a package and
save it as a dependency in the package.json file.

Press ^C at any time to quit.
package name: (ex) exampleapp
version: (1.0.0)
description: Example application on Koa and PostgreSQL
entry point: (index.js)
test command:
git repository:
keywords:
author: Nariman Safiulin <woofilee@gmail.com>
license: (ISC)
About to write to <..>\package.json:

{
"name": "exampleapp",
"version": "1.0.0",
"description": "Example application on Koa and PostgreSQL",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "Nariman Safiulin <woofilee@gmail.com>",
"license": "ISC"
}


Is this ok? (yes)

You should see the package.json file that NPM has created.

Install koa:

1
$ npm i koa

Also we need something for requests routing. We will use a koa-router - popular and full-featured package.
Another one - koa-logger - for development logging.

1
$ npm i koa-router koa-logger

For database we will use a koa-mongo driver.

1
$ npm i koa-mongo

MongoDB

About Mongo

MongoDB is a free and open-source cross-platform document-oriented database program. MongoDB realises a new approach to building databases: no tables, schemas, SQL-queries, foreign keys and other things connected with relational databases.

Installation

You can download MongoDB installer from here. There you can choose between Community and Enterprise versions.
After downloading you have to create a directory on your hard drive that will contain Mongo databases. By default, in Windows OS it is C:\data\db, so if you use Windows, you have to create this directory. In Linux and MacOS it is /data/db.
If you need to use another path, you can use --dbpath flag when server starts.

Starting the server

After creating the directory for databases you can start MongoDB server. It is a mongod application in bin directory. Start the command propmt in Windows or the terminal in Linux and use the following commands. For Windows (if MongoDB is loaded in C:\mongodb):

1
2
cd c:\mongodb\bin
mongod

Command prompt will show you some service staff, for example, server localhost is running on port 27017.
If your databases located in another directory (for example, d:\test\mongodb\data), use the following command:

1
C:\mongodb\bin\mongod.exe --dbpath d:\test\mongodb\data

After successful starting of the server, we can use mongo shell to connect to databases. This file is located in …\mongodb\bin too:

1
2
cd c:\mongodb\bin
mongo

If the installation of Mongo and starting of the server were successful, the command prompt will be waiting for queries to DB.
By default, MongoDB does not use any methods of authorization to access the database. The developers of MongoDB think that the application must contain all the logic. Database is only needed for data storage and management. Therefore, in this article, a authorized connection will not be considered.
The database will be automatically created with the first insert query.
You can exit by typing ‘exit’.

Hello, World!

Create file app.js and copy the next code. It’s a modified version of standart Koa example.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
const Koa = require('koa');
const Router = require('koa-router');
const Logger = require('koa-logger');

const app = new Koa();
const router = new Router();

// Response to the World to the GET requests
router.get('/', async (ctx) => {
ctx.body = 'Hello, World!\n';
});

// Response by name to the GET requests, :name is URL fragment/argument
router.get('/:name', async (ctx) => {
ctx.body = `Hello, ${ctx.params.name}!\n`;
});

// Development logging
app.use(Logger());
// Add routes and response to the OPTIONS requests
app.use(router.routes()).use(router.allowedMethods());

// Listen the port
app.listen(3000, () => {
console.log('Server running on port 3000');
});

Now you can start the server:

1
$ node app.js

If the server has successfully started, open the browser and go to http://localhost:3000/. You should see the Hello, World! page. Also, try to type your name, for example, http://localhost:3000/Elisey.
In your terminal you should see something like that:

1
2
3
4
5
6
node app.js
Server running on port 3000
<-- GET /
--> GET / 200 19ms 14b
<-- GET /Elisey
--> GET /Elisey 200 3ms 15b

Let’s connect to the database.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
'use strict';
//Require an appropriate module
const Mongo = require('koa-mongo');
// Use Mongo
app.use(Mongo());

//For empty GET-request
router.get('/', async (ctx) => {
//Find necessary document with "find" method in collection "first_collection"
const result = await ctx.mongo.db('test').collection('first_collection').find({ text: "Hello, world!" }).toArray();
//If there is no document, add it with "insert" method
if (result.length === 0)
ctx.mongo.db('test').collection('first_collection').insert({ text: "Hello, world!" });
var helloWorld = await ctx.mongo.db('test').collection('first_collection').find({ text: "Hello, world!" }).toArray();
ctx.body = helloWorld[0].text;
});

// Similary with "named" GET-requests
router.get('/:name', async (ctx) => {
const result = await ctx.mongo.db('test').collection('first_collection').find({ text: ctx.params.name }).toArray();
if (result.length === 0)
ctx.mongo.db('test').collection('first_collection').insert({ text: ctx.params.name });
var name = await ctx.mongo.db('test').collection('first_collection').find({ text: ctx.params.name }).toArray();
name = name[0].text;
ctx.body = `Hello, ${name}!\n`;
});

Save and restart the server to see the result.

Simple application w/ Node.js + Koa + PostgreSQL

From Koa introduction:

Koa is a new web framework designed by the team behind Express, which aims to be a smaller, more expressive, and more robust foundation for web applications and APIs. Through leveraging generators Koa allows you to ditch callbacks and greatly increase error-handling. Koa does not bundle any middleware within core, and provides an elegant suite of methods that make writing servers fast and enjoyable.

Requirements

Koa requires Node 7.6.0 or higher for async/await syntax.
You can use older Node versions with Babel (see more about it at Koa installation section).
PostgreSQL version does not matter. We will use the latest one.

Environment

Node.js

If Node is not installed yet, you can download it here. If you are a lucky owner of Linux or macOS, package managers can be used - this method described here.
To check that the Node installation is correct, you can run the command:

1
$ node --version

That will print the Node version.
Also for NPM:

1
$ npm --version

Dependencies installation

Create directory where all the code will be located. Run terminal and open this directory.

Let’s initialize the package environment:

1
$ npm init

NPM will ask you a few questions. Type answers for package name of author.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
$ npm init

This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sensible defaults.

See `npm help json` for definitive documentation on these fields
and exactly what they do.

Use `npm install <pkg>` afterwards to install a package and
save it as a dependency in the package.json file.

Press ^C at any time to quit.
package name: (ex) exampleapp
version: (1.0.0)
description: Example application on Koa and PostgreSQL
entry point: (index.js)
test command:
git repository:
keywords:
author: Nariman Safiulin <woofilee@gmail.com>
license: (ISC)
About to write to <..>\package.json:

{
"name": "exampleapp",
"version": "1.0.0",
"description": "Example application on Koa and PostgreSQL",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "Nariman Safiulin <woofilee@gmail.com>",
"license": "ISC"
}


Is this ok? (yes)

You should see the package.json file that NPM has created.

Install koa:

1
$ npm i koa

Also we need something for requests routing. We will use a koa-router - popular and full-featured package.
Another one - koa-logger - for development logging.

1
$ npm i koa-router koa-logger

For database we will use a node-postgres driver. It’s a simple client, not a ORM.

1
$ npm i pg

PostgreSQL

You can download PostgreSQL here with a portable binaries for fast start w/o installation proccess.
To check the PostgreSQL installation, run the command:

1
$ sudo -u postgres psql

On Windows (type your own Windows user name instead of postgres, if you didn’t create a database manually):

1
> psql -U postgres

On Linux and macOS a PostgreSQL server should be running yet after installation via package manager.
Otherwise, or if you have Windows, follow next commands:

1
2
> initdb -U postgres -D data
> pg_ctl -D data start

A default postgres database username is recommended, data - a database storage directory, you can provide any other path.
After that a pg_ctl command will start the PostgreSQL server (provide a path to the database storage).

Check again, you should see a PostgreSQL prompt:

1
postgres=#

Type \q to exit.

Default database postgres was created for us.

Hello, World!

Create file app.js and copy the next code. It’s a modified version of standart Koa example.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
const Koa = require('koa');
const Router = require('koa-router');
const Logger = require('koa-logger');

const app = new Koa();
const router = new Router();

// Response to the World to the GET requests
router.get('/', async (ctx) => {
ctx.body = 'Hello, World!\n';
});

// Response by name to the GET requests, :name is URL fragment/argument
router.get('/:name', async (ctx) => {
ctx.body = `Hello, ${ctx.params.name}!\n`;
});

// Development logging
app.use(Logger());
// Add routes and response to the OPTIONS requests
app.use(router.routes()).use(router.allowedMethods());

// Listen the port
app.listen(3000, () => {
console.log('Server running on port 3000');
});

Now you can start the server:

1
$ node app.js

If the server has successfully started, open the browser and go to http://localhost:3000/. You should see the Hello, World! page. Also, try to type your name, for example, http://localhost:3000/Nariman.
In your terminal you should see something like that:

1
2
3
4
5
6
7
8
9
10
11
$ node app.js

Server running on port 3000
<-- GET /
--> GET / 200 13ms 14b
<-- GET /favicon.ico
--> GET /favicon.ico 200 7ms 20b
<-- GET /Nariman
--> GET /Nariman 200 10ms 16b
<-- GET /favicon.ico
--> GET /favicon.ico 200 7ms 20b

Let’s connect to the database.
We will use the connection pool, because it’s a common way to use database drivers, especially for PostgreSQL. Pool has advatages over manual connections, due to each new manual connection can take some time for connection establishment and it requires some management to control the number of simultaneous connections.

Add the dependency:

1
const { Pool } = require('pg');

Right before the server booting code (before app.listen call):

1
2
3
4
5
6
7
app.pool = new Pool({
user: 'postgres',
host: 'localhost',
database: 'postgres',
password: '', // Password is empty be default
port: 5432, // Default port
});

Then, change our routes, to query database for Hello string.

1
2
3
4
5
6
7
8
9
router.get('/', async (ctx) => {
const { rows } = await ctx.app.pool.query('SELECT $1::text as message', ['Hello, World!'])
ctx.body = rows[0].message;
});

router.get('/:name', async (ctx) => {
const { rows } = await ctx.app.pool.query('SELECT $1::text as message', [`Hello, ${ctx.params.name}!`])
ctx.body = rows[0].message;
});

Note that Koa can auto-translate the result into JSON, if the response is not a string. If you just return rows, you’ll see the JSON response.

Save and restart the server.

In conclusion

We wrote everything in one file. Of course, for a real project, you should create the project structure, and also take care of closing the PostgreSQL pool and Koa connections when shutting down the server.

You can also use other database libraries, like Sequelize, Bookshelf, Massive.

References

Review of frameworks for creating a server application on nodejs

What is Node.js?

Node or Node.js is a server implementation of the JavaScript programming language, based on the V8 engine. It is designed to create scalable distributed network applications, such as a web server. Node.js for purposes of use is similar to Twisted frameworks in Python and EventMachine in Ruby. Unlike most JavaScript programs, this framework is executed not on the client’s browser, but on the server side.

What is framework?

framework is a set of tools, libraries, good code that will help turn routine tasks into modules that can be used repeatedly. The task of the framework is to allow the designer or developer to focus on tasks that are unique within this project. In other words, do not reinvent the wheel time after time.

Now the frameworks themselves

Consider such auxiliary tools for server development on JS, like:

  • Express
  • Meteor
  • Mean
  • Koa
  • Hapi
  • Sails
  • Socket

Express

Express is a minimalistic and flexible web framework for Node.js applications, providing an extensive set of functions for mobile and web applications.

Express, as is well known, develops its own way, unlike other frameworks that rely heavily on Rails, but also borrowed a lot from another Ruby framework called Sinatra. The concept is simple: the framework provides enough opportunities for starting and running “on the fly”, without requiring much time for preparation.

This is the framework that makes the creation of most sites very simple. The first thing you need to do is install it.
$ npm install express --save
Together with the site node, you will have the npm command. This tool gives you access to a huge number of modules created by the community, and Express is just one of them.

Pluses of this framework:

1) Low entry threshold, Express is practically the standard Node.js-application.
2) Complete customization.

Minuses:

1) All resources must be created manually and, as a result, there will be a lot of repeated code or worse - own library.
2) Each resource requires testing or a simple check for the 500th error.
3) Refactoring will become painful, as it will be necessary to rule everything and everywhere.
4) There is no standard approach, you need to look for your own.
->Example of development on Express
->Official site

Meteor

Meteor is an MVC (Model-View-Controller) open source framework, with which you can create real-time Web applications. One of the most important features of the platform is that it allows you to use the same code both on the server side and on the client side. Between the server and the client, as a rule, data is transferred, but not HTML-code. The framework supports OS X, Windows and Linux. Its reactive programming model allows you to create applications using less JavaScript code.

Pluses of this framework:

1) The server and client code is written in one language
2) Conveniently debug the code directly from the browser
3) You can quickly demonstrate the status of the project to the client using meteor deploy

Minuses:

1) Not suitable for large projects
2) Not at all suitable for mobile devices due to the large amount of JavaScript
3) In the code some trivial problems have to be solved with the help of cumbersome constructions
->Example of development on Meteor
->Official site

Mean

MEAN (an abbreviation of MongoDB, Express.js, Angular.js, Node.js) is a set of server software that is used for web development. At the client, server, and database level, the entire MEAN stack is written in JavaScript. Displacement of the base platform from the OS (Linux) to the runtime JavaScript (Node.js) carries with it independence from the OS: Node.js runs on Windows and OS X as well as on Linux.

The main shift MEAN is the transition from the traditional generation of server-side pages to targeting single-page applications (SPAs) on the client side.
->Example of development on Mean
->Official site

Koa

The development team of the Express.js framework created another framework called Koa.js - the next generation futuristic framework for Node.js, which promises to be more concise and vivid in comparison with Express.js. Koa.js is focused on creating web applications and APIs, its main advantage is generators, which are an excellent way to avoid callbacks, and help developers in correcting errors.
->Example of development on koajs
->Official site

Hapi

Less well-known framework, which is developed by the team of Walmart Labs. Unlike Express, it has a slightly different approach, which provides more functionality right out of the box. The pluses include full control over the reception of requests and a detailed reference with the generation of documentation.

Pluses of this framework:

1) Full control over the reception of requests.
2) Detailed reference with the generation of documentation.

Minuses:

1) hapi, as well as Express, gives excellent opportunities, but how to use them, you must understand yourself.
->Official site

Sails

Sails.js is an MVC (Model-View-Controller) framework that allows you to easily and quickly create Node.js applications. Sails.js is best suited for creating real-time applications. It is based on the MVC pattern, like Ruby on Rails, but also supports the requirements of modern applications: software interfaces with a scalable, service-oriented architecture. This framework is particularly suitable for the development of chat rooms, real-time toolbars and multiplayer games.
->Offcial site

Socket

Socket. IO - JavaScript library for web applications and real-time data exchange. It consists of two parts: client, which runs in the browser and server for node.js. Both components have a similar API.

Pluses:

1) Powerful and easy to use
2) Used by many large companies
->Offisial site
->Using the Socket library
->One more example

Conclusion

Actually, on this we examined several frameworks for server development on JS. For a more detailed dive, you need to use links to official sites.

Инструкция по созданию серверного приложения на nodejs + express + mongoDB


Для понимания подойдет простейший пример, в котором мы сможем создавать, читать, обновлять и удалять простые текстовые документы

Установка компонентов

На официальном сайте node (https://nodejs.org/) есть подробные инструкции по установке
Примеры для самого распространенного, если не хочется переходить и искать

Для centos:

1
2
3
$ curl —silent —location https://rpm.nodesource.com/setup_9.x | sudo bash -
$ sudo yum -y install nodejs
$ sudo yum install gcc-c++ make

Для ubuntu:

1
2
3
$ curl -sL https://deb.nodesource.com/setup_9.x | sudo -E bash -
$ sudo apt-get install -y nodejs
$ sudo apt-get install -y build-essential

Затем организуем папку для проекта и в ней выполняем команду для его инициализации:
initialization in it:

1
$ npm init

Отвечаем на вопросы следующие вопросы

  • Название проекта
  • Версия проекта
  • Описание проекта
  • Входная точка
  • Команда на тестирование
  • Репозиторий гитхаба
  • Ключевые слова проекта
  • Автор проекта
  • Лицензия
И подтверждаем, после чего в папке появляется файл package.json, описывающий проект

Теперь установим оставшиеся компоненты: Express и MongoDB(последняя версия плагина некорректно работает с БД, так что лучше установить более раннюю):

1
$ npm install --save express mongodb@2.2.16

Так же для удобства обработки url-encoded запросов устанавливаем body-parser:

1
$ npm install --save body-parser

И для удобства разработки хорошо бы установить Nodemon, который каждый раз будет перезапускать сервер, когда будут изменяться какие-либо файлы:

1
$ npm install --save-dev nodemon

А дальше для подключения Nodemon надо добавить следующее в package.json:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
{
"name": "notable",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error^ no test specified\" && exit 1",
"dev": "nodemon server.js"
},
"author": "",
"license": "ISC",
"dependencies": {
"body-parser": "^1.18.2",
"express": "^4.16.2",
"mongodb": "^2.2.16"
},
"devDependencies": {
"nodemon": "^1.14.2"
}
}

Чтобы тестировать наше приложение установим postman(https://www.getpostman.com/) – он будет имитировать запросы

Запуск сервера

Создадим файл server.js,в котором пропишем зависимости (то с чем будет работать сервер), укажем порт и запустим прослушивание:

1
2
3
4
5
6
7
8
const express        = require('express');
const MongoClient = require('mongodb').MongoClient;
const bodyParser = require('body-parser');
const app = express();
const port = 8080;
app.listen(port, () => {
console.log('We are live on ' + port);
});

Запустим сервер:

1
npm run dev

В терминале теперь можно видеть сообщение “We are live on port 8080”

Структура проекта

Для более удобного структурирования проекта стоит создать папку app, в ней создаем папку routes, а в ней – файлы index.js и note_routes.js

Таким образом структура выглядит так: в app/routes – наши обработчики маршрутов, в папке node_modules – модули нашего проекта, а server.js непосредственно описывает наш сервер.

Подключение БД

В корень проекта добавляем директорию config, создаем в ней файл db.js.
В файл db.js пишем следующее:

1
2
3
module.exports = {
url : 'mongodb://localhost:27017/<yourDataBase>'
};

А в файл server.js добавляем:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
const express        = require('express');
const MongoClient = require('mongodb').MongoClient;
const bodyParser = require('body-parser');
const db = require(‘./config/db’);
const app = express();
const port = 8080;
app.use(bodyParser.urlencoded({ extended: true }));
MongoClient.connect(db.url, (err, database) => {
if (err) return console.log(err)
require(‘./app/routes’)(app, database);
app.listen(port, () => {
console.log('We are live on ' + port);
});
});

Создание текстового документа

В app/routes/note_routes.js пишем:

1
module.exports = function(app, db) { };

В app/routes/index.js:

1
2
3
4
5
6
7
8
9
10
11
12
13
const noteRoutes = require('./note_routes');
module.exports = function(app, db) {
app.post('/notes', (req, res) => {
const note = { text: req.body.body, title: req.body.title };
db.collection('notes').insert(note, (err, result) => {
if (err) {
res.send({ 'error': 'An error has occurred' });
} else {
res.send(result.ops[0]);
}
});
});
};

Чтение документа

По аналогии с app.post, пишем другой метод:

1
2
3
4
5
6
7
8
9
10
11
app.get('/notes/:id', (req, res) => {
const id = req.params.id;
const details = { '_id': new ObjectID(id) };
db.collection('notes').findOne(details, (err, item) => {
if (err) {
res.send({'error':'An error has occurred'});
} else {
res.send(item);
}
});
});

Удаление документа

По аналогии с app.post, пишем другой метод:

1
2
3
4
5
6
7
8
9
10
11
app.delete('/notes/:id', (req, res) => {
const id = req.params.id;
const details = { '_id': new ObjectID(id) };
db.collection('notes').remove(details, (err, item) => {
if (err) {
res.send({'error':'An error has occurred'});
} else {
res.send('Note ' + id + ' deleted!');
}
});
});

Обновление документа

По аналогии с app.post, пишем другой метод:

1
2
3
4
5
6
7
8
9
10
11
12
app.put ('/notes/:id', (req, res) => {
const id = req.params.id;
const details = { '_id': new ObjectID(id) };
const note = { text: req.body.body, title: req.body.title };
db.collection('notes').update(details, note, (err, result) => {
if (err) {
res.send({'error':'An error has occurred'});
} else {
res.send(note);
}
});
});

Тестирование

Postman позволяет указывать тип запроса (get, post, put, update), адрес и порт для запроса, а также добавлять в тело запроса различные параметры, например, пустой POST-запрос на 8080 порт.
По выполнении запроса, мы видим ответ сервера

alt-текст
Пример POST-запроса с заполненным телом:

alt-текст
Пусть сервер выводит запрос в консоль сервера, тогда мы увидим:

alt-текст

Ссылки

Для установки node
https://nodejs.org/en/download/package-manager/#enterprise-linux-and-fedora
Для установки postman
https://www.getpostman.com/
Аналогичные статьи

  1. https://medium.freecodecamp.com/building-a-simple-node-js-api-in-under-30-minutes-a07ea9e390d2#.eybmlr1g9
  2. https://habrahabr.ru/company/ruvds/blog/321104/
  3. https://loftblog.ru/material/4-podklyuchenie-bazy-dannyx-k-express/
  4. http://coenraets.org/blog/2012/10/creating-a-rest-api-using-node-js-express-and-mongodb/

Инструкция по созданию серверного приложения на nodejs + express + postgresql

Установка Node.js

Windows:

Для того чтобы начать, зайдите на страницу загрузки Node.js (https://nodejs.org/en/download/). Выберите установщик, который вы хотите скачать и установить.

После запускаем установщик и пошагово завершаем установку.

CentOS:

Для установки Node.js нужно подключиться к серверу по протоколу SSH. После этого, нужно установить последнюю версию .nodejs из репозиториев. Для этого:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
$ yum update

//Устанавливаем группу Development Tools
$yum -y groupinstall "Development Tools"

//Вводим команду для подключения к серверу и создания нескольких параллельных сессий
$ yum -y install screen

//Переходим в папку /usr/src и загружаем архив с Node.js
$ cd /usr/src
$ wget http://nodejs.org/dist/v0.10.4/node-v0.10.4.tar.gz

//Извлекаем файлы из архива и помещаем в каталог
$ tar zxf node-v0.10.4.tar.gz
$ cd node-v0.10.4

//Cоздаем установочный файл и запускаем
$ make
$ make install

Node.js установлен. По умолчанию его двоичный код лежит в /usr/local/bin/node.

Ubuntu

Для установки Node и npm при помощи apt-get, запустите следующие команды:

1
2
3
4
$ sudo apt-get update  
$ sudo apt-get install nodejs
$ sudo ln -s /usr/bin/nodejs /usr/bin/node
$ sudo apt-get install npm

Если вы все еще хотите использовать apt-get, но вам необходима наиболее свежая версия Node, стоит воспользоваться иным методом.

Он очень похож на предыдущий, но мы будем запускать скрипт, указывающий менеджеру пакетов, где хранится последняя версия.

1
2
3
4
5
6
7
8

$ curl -sL https://deb.nodesource.com/setup_5.x | sudo -E bash -
$ sudo apt-get install -y nodejs
$ sudo ln -s /usr/bin/nodejs /usr/bin/node

```

Чтобы проверить, что у вас установлена Node.js и проверить версию, выполните:

$ node –version

1
2

Чтобы начать работу, выполните в командной строке:

$ node

1
2
3
4

### Установка зависимостей.

Вы можете интерактивно генерировать файл *package.json* с помощью команды *npm init* в терминале.

$ npm init

1
2
3
4

После запуска команды вас попросят ввести некоторые данные. После их получения *package.json* будет автоматически сгенерирован и помещен в папку вашего приложения.

Если какие-либо зависимости не установлены, то добавить их в своё приложение можно следующей командой:

npm install[module name] –save

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15


### Установка PostgreSQL.

PostgreSQL является очень популярным сервером баз данных, поэтому присутствует в официальных репозиториях Ubuntu. Однако в PPA разработчиков PostgreSQL можно найти самую свежую версию.

**Windows**

Скачать PostgreSQL можно со страницы загрузки официального сайта вот здесь - http://www.postgresql.org/download/windows/

Загрузить установщик, выбрав версию, подходящую под разрядность системы и следовать шагам, предлагаемым установщиком.

**CentOS**

Для установки самой свежей версии необходимо добавить официальный репозиторий следующей командой:

$ sudo rpm -Uvh http://yum.postgresql.org/9.5/redhat/rhel-7-x86_64/pgdg-centos95-9.5-2.noarch.rpm

1
2
После того как репозиторий будет добавлен к вашей системе вы можете перейти к установке программы. 
Установка Postgresql CentOS выполняется командой:

$ sudo yum install postgresql96-server postgresql96

1
Сразу после установки Postgresql сервер еще не готов к использованию, нужно инициализировать необходимые базы данных. Для этого выполните:

$ /usr/pgsql-9.6/bin/postgresql96-setup initdb

1
2
3
4

**Ubuntu:**

Добавьте репозиторий PostgreSQL в системный список источников:

$ sudo sh -c ‘echo “deb http://apt.postgresql.org/pub/repos/apt/ lsb_release -cs-pgdg main” >> /etc/apt/sources.list.d/pgdg.list’

1
и добавьте для него ключ:

$ wget -q https://www.postgresql.org/media/keys/ACCC4CF8.asc -O - | sudo apt-key add -

1
Это позволит при обновлении пакетов получать наиболее свежие версии.

initdb -U postgres -D data
pg_ctl -D data start
psql -U postgres

1
2
3
4
5

Здесь *postgres* - это имя пользователя, лучше его указать по умолчанию, для начала, а *data* - директория, где будут храниться базы, можно указать любую удобную.
После чего *pg_ctl* запускает PostgreSQL (с указанием директории с базами).

По окончанию, мы должны увидеть приветственную консоль:

postgres=#

1
2
3
4

### Установка Express.

Чтобы установить Express и добавить в список зависимостей, необходимо перейти в папку с проектом и оттуда запустить команду:

$ npm install express –save

1
2
3
4

### Создание простого серверного приложения.

Создайте директорию, где будет храниться ваш проект.

$ mkdir nodejs-express-postgresql/
$ cd nodejs-express-postgresql/

1
Теперь необходимо иниицировать наше приложение:

$ npm init -y

1
2
3
4

Эта команда создаст *package.json* со стандартными настройками конфигурации.

Теперь создадим файл с нашим приложением.

$ touch app.js

1
2

Теперь набоходимо подключить и настроить Express.

const express = require(‘express’);
const bodyParser = require(‘body-parser’);

// Set up the express app
const app = express();

// Setup a default catch-all route that sends back a welcome message in JSON format.
app.get(‘*’, (req, res) => res.status(200).send({
message: ‘Welcome, my frined.’,
}));

module.exports = app;

1
2

Теперь если мы запустим наш сервер

npm run start:dev

1
2
3
4
5
6
7

И перейдем по http://localhost:8000/, то у нас появится сообщение *Welcome, my friend.*

Теперь необходимо подключить нашу базу данных.
Мы будем сразу же использовать пул, а не отдельные подключения. Это распространенная практика, тем более для PostgreSQL. Пул позволяет хранить несколько соединений, тем самым не тратя время на их создание и не заниматься их менеджементом.

Сперва настроим зависимость, потом добавим подключение к нашей базе.

const Pool = require(‘pg’).Pool;

1
По умолчанию в *PostgreSQL* нет пароля, а стандартным портом является - 5432.

const config = {
user: ‘postgres’,
host: ‘localhost’,
database: ‘users’,
password: ‘’,

};

const pool = new Pool(config);

1
2

Теперь только остаётся сделать нашу функцию, которая будет показывать все записи из таблицы *users*.

(async () => {
const client = await pool.connect()
try {
const res = await pool.query(“select * from users”);
console.log(res.rows[0])
} finally {
client.release()
}
})().catch(e => console.log(e.stack))

```

Теперь при перезагрузке нашего сервера можно будет увидеть результат.

Материалы и полезные ссылки, используемвые в работе.

PostgreSQL:
https://node-postgres.com/
http://expressjs.com/ru/guide/database-integration.html

Node.js:
https://nodejs.org/en/
https://medium.com/devschacht/node-hero-chapter-1-239f7afeb1d1
https://node-postgres.com/features/pooling

Express:
http://expressjs.com/ru/

NPM:
https://www.npmjs.com/