Kselax.ru

Hacker Kselax – the best hacker in the world

Menu
  • Blog
  • Contacts
  • wp plugin generator
  • English
    • Русский
Menu

Category: node.js

express.js adding a router with the regular expression

Posted on 8 June, 2019 by admin

You can create a route with express that will handle a few pages like portfolio, projects, reviews, using such a structure as shows below

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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
const express = require('express');
const router = express.Router();
 
const DB = require('../../core/my_db/DB.js')
 
 
 
// # 1
/* /api/v1/users/:login/portfolio/?user&portfolio */
router.get(/\/(.*)\/(portfolio|projects|reviews)/, function(req, res, next) {
  let login = req.params[0]
  
  const getUser = (login) => {
    return new Promise((resolve, reject) => {
      DB.pool.query(
        `SELECT *
         FROM `users`
         WHERE login = ?`,
        [login],
        (err, r) => {
          if (err) throw err
          if (r.length === 1) {
            delete r[0].pass
            return resolve({ user: r[0] })
          }
          return reject({ error: "notFound" })
        }
      )
    })
  }
 
  const getPortfolio = (login) => {
    return new Promise((resolve, reject) => {
      DB.pool.query(
        `SELECT p.*
         FROM `users` u
         INNER JOIN `portfolios` p
         ON p.userId = u.id AND u.login = ?`,
        [login],
        (err, r) => {
          if (err) throw err
          resolve({ portfolios: r })
        }
      )
    })
  }
 
  const getProjects = (login) => {
    return new Promise((resolve, reject) => {
      DB.pool.query(
        `SELECT p.*
        FROM `users` u
        INNER JOIN `projects` p
        ON p.userId = u.id AND u.login = ?`,
        [login],
        (err, r) => {
          if (err) throw err
          resolve({ projects: r })
        }
      )
    })
  }
 
  const getReviews = (login) => {
    return new Promise((resolve, reject) => {
      DB.pool.query(
        `SELECT r.*,
            u2.id as u2_id,
            u2.login,
            u2.avatar,
            u2.firstName,
            u2.secondName
        FROM `users` u
        INNER JOIN `reviews` r
        ON r.userId = u.id AND u.login = ?
        INNER JOIN `users` u2
        ON r.authorId = u2.id`,
        [login],
        (err, r) => {
          if (err) throw err
          resolve({ reviews: r })
        }
      )
    })
  }
 
  
 
  let requests = []
  console.log('req.query = ', req.query);
 
  if (req.query.hasOwnProperty('user')) {
    requests.push(getUser(login))
  }
 
  if (req.query.hasOwnProperty('portfolio')) {
    requests.push(getPortfolio(login))
  }
 
  if (req.query.hasOwnProperty('projects')) {
    requests.push(getProjects(login))
  }
 
  if (req.query.hasOwnProperty('reviews')) {
    requests.push(getReviews(login))
  }
  
  
  
 
  
 
  Promise.all(requests)
    .then(values => {
      console.log(values); // [3, 1337, "foo"]
      res.json(values)
    })
    .catch(err => {
      res.json(err)
    })
  
  
});
 
 
 
// # 2
/* /api/v1/users/:login/projects/ */
router.get('/:login/projects/', function(req, res, next) {
  res.json({ hello:'world' })
})
 
module.exports = router;

  It’s very important the line that specifies the regex should be a js regular expression. Not a string!

1
router.get(/\/(.*)\/(portfolio|projects|reviews)/, function(req, res, next) {

    the end

Read more
jwt authentication with passport.js

How to use JWT with passport.js

Posted on 18 May, 201918 May, 2019 by admin

#Content table: Preface Installation Create the authentication router Implementation of a JWT protected router Test the JWT authentication and authorization Conclusions A few words about https and http all the code files /routers/auth.js, /routers/users.js, /app/passport.js and app.js Resources   #Preface JWT is a json web token. It is used for authentication between server and client….

Read more

Puppeteer sclerotic

Posted on 13 February, 201926 February, 2019 by admin

Content table   Some Important tips networkidle0 – use with SPA apps that uses fetch requests networkidle2 – use with pages that do long pulling and other side activity   How to create a simple example   #Needed libs with ubuntu 16.04 after installing on a new server important: an error when installing on the…

Read more

PM2 sclerotic

Posted on 13 February, 201919 February, 2019 by admin

How to run npm start with pm2

1
pm2 start npm -- start

  How to run PM2 on rebooting the system At first you have to run the command

1
$ pm2 startup

you’ll get

1
2
3
4
5
neo@v137625:~/node.js/scrapper-ros-acreditation1/server$ pm2 startup
[PM2] Init System found: systemd
[PM2] To setup the Startup Script, copy/paste the following command:
sudo env PATH=$PATH:/usr/local/bin /usr/local/lib/node_modules/pm2/bin/pm2 startup systemd -u neo --hp /home/neo
neo@v137625:~/node.js/scrapper-ros-acreditation1/server$

Coppy the command and you’ll get something like that like that

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
38
39
40
41
42
neo@v137625:~/node.js/scrapper-ros-acreditation1/server$ sudo env PATH=$PATH:/usr/local/bin /usr/local/lib/node_modules/pm2/bin/pm2 startup systemd -u neo --hp /home/neo
[PM2] Init System found: systemd
Platform systemd
Template
[Unit]
Description=PM2 process manager
Documentation=https://pm2.keymetrics.io/
After=network.target
 
[Service]
Type=forking
User=neo
LimitNOFILE=infinity
LimitNPROC=infinity
LimitCORE=infinity
Environment=PATH=/usr/local/bin:/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin
Environment=PM2_HOME=/home/neo/.pm2
PIDFile=/home/neo/.pm2/pm2.pid
 
ExecStart=/usr/local/lib/node_modules/pm2/bin/pm2 resurrect
ExecReload=/usr/local/lib/node_modules/pm2/bin/pm2 reload all
ExecStop=/usr/local/lib/node_modules/pm2/bin/pm2 kill
 
[Install]
WantedBy=multi-user.target
 
Target path
/etc/systemd/system/pm2-neo.service
Command list
[ 'systemctl enable pm2-neo' ]
[PM2] Writing init configuration in /etc/systemd/system/pm2-neo.service
[PM2] Making script booting at startup...
[PM2] [-] Executing: systemctl enable pm2-neo...
Created symlink from /etc/systemd/system/multi-user.target.wants/pm2-neo.service to /etc/systemd/system/pm2-neo.service.
[PM2] [v] Command successfully executed.
+---------------------------------------+
[PM2] Freeze a process list on reboot via:
$ pm2 save
 
[PM2] Remove init script via:
$ pm2 unstartup systemd
neo@v137625:~/node.js/scrapper-ros-acreditation1/server$

  Now, you have to run one or a few processes in PM2 and…

Read more

node.js fs – sclerotic

Posted on 12 December, 201816 February, 2019 by admin

  #How to read write files synchronously with fs

1
2
3
4
5
6
7
8
9
10
11
const fs = require('fs')
 
const str = '1Hello world!'
 
// save data
fs.writeFileSync(`${__dirname}/data.html`, str)
 
// read data
const d = fs.readFileSync(`${__dirname}/data.html`, 'utf8')
 
console.log('d = ', d) // d =  1Hello world!

  #How to read write files asynchronously with fs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
const fs = require('fs')
 
const str = 'Hello world!'
 
// save data
fs.writeFile(`${__dirname}/data.html`, str, err => {
  if (err) throw err
  console.log('saved');
})
 
// read data
fs.readFile(`${__dirname}/data.html`, 'utf8', (err, data) => {
  if (err) throw err
  console.log('data = ', data); // data =  Hello world!
})

    #How to check existence of files Sometimes we have to know whether a file exists or not. To do this we’ll be using a node.js fs module. We could check synchronously by using and…

Read more

How to enable babel with nodejs and express

Posted on 28 November, 201829 November, 2018 by admin

How to set up node.js with a ES6 support. You have to use them to modules that will allow you to wrap the server in a babel wrapper and the code will be work.

Read more

How to work with node.js modules

Posted on 17 November, 201813 February, 2019 by admin

What is going on when we do require(‘some module’)? What if I want to include the MySQL module to my a few modules and use the same connection, how to have we include it properly? In this article, we’ll try to figure out how the node.js modules work. #How to make your own module Create a…

Read more
graphql

How to use graphql in node.js

Posted on 14 November, 201814 November, 2018 by admin

Graphql is a query language for an API link graphql.js documentation link It is usually used with express by using module express-graphql link The sense of using at first we create a schema and in a graphql language then we create a root this is a variable that has handlers for each element in a schema….

Read more
passportjs authentication

How to use passportjs with node.js

Posted on 6 November, 201814 November, 2018 by admin

  Links: the official site passportjs Look at my example on GitHub link   Table contents:   #Passportjs the usage scheme Usually you have to implement such a steps: create passport.serializeUser create passport.deserializeUser  passport.use(new SteamStrategy({options}, callback)  initialize the session, passport should be initialized afterward add two routers /auth/steam and /auth/steam/return   #Passportjs general functions #Passport serialize…

Read more
template engine

JavaScript templates for rendering pages

Posted on 1 November, 20183 November, 2018 by admin

Exists many JavaScript templates like handlebars, ejs, pug, etc. In this article I’ll overview some templates that I’ve used first of all it’s my the first template handlebars, I use the module express-handlebar   links: How to integrate express with pug. The official guide link consolidate.js link Github repository with examples of this article link  …

Read more

Posts navigation

  • 1
  • 2
  • 3
  • Next

Categories

  • bash (1)
  • English (9)
  • JavaScript (4)
  • node.js (22)
  • photoshop (1)
  • php (3)
  • React (9)
  • sclerotic (6)
  • Ubuntu (10)
  • Uncategorized (13)
  • Wordpress (1)

Tags

Ajax apache2 automation bash chrome-extension command line editor ejs email English English-grammar framework functions git graphql handlebars hybrid app installation javascript js linux newbie node.js node.js javascript nodemailer npm objects Performance php phpmyadmin playonlinux promise rabbitmq React react-router redis reverse-proxy session shell socket.io sublime text 3 time zones ubuntu unity webpack

Recent Comments

  • damien on How to install npm and nodejs the latest versions on ubuntu
  • Cam on How to install npm and nodejs the latest versions on ubuntu
  • Pierre on socket.io with apache as a reverse proxy on the CentOS
  • admin on How to use react-router with a few languages
  • admin on How to install npm and nodejs the latest versions on ubuntu
©2021 Kselax.ru Theme by ThemeGiant