Базовый JS и Node.js

Лекция 02


var, let, const

for, while, do while

if, else, else if,
switch

Boolean, Number, String, Object, Symbol,
Null, Undefined

console.log

// Single-line comment
/*
    Multi-line comment
*/

try {...} catch(error) {...} finally {...}
            


function / first class object

function sum(a, b, c) { ... }
function (a, b, c) { ... }
(a, b, c) => {...}

const sum = function (a, b, c) { ... };
const sum = (a, b, c) => {...};
            


// Hoisting
/* -Correct- */
sum(1, 2, 3);

function sum(a, b, c) { ... }
            


// Hoisting
/* -Incorrect- */
sum(1, 2, 3);

const sum = function (a, b, c) { ... };
            


// Hoisting
/* -Correct- */
const sum = function (a, b, c) { ... };

sum(1, 2, 3);
            


// Arguments
function sum() {
  const sum = 0;

  for (let i = 0; i < arguments.length; i++) {
    sum += arguments[i];
  }
}
            


// Objects
const hero = {
  name: 'John Snow',
  title: 'King of the North'
};

console.log( hero.name );
console.log( hero['name'] );
            


// Objects
const hero = {
  name: {
    first: 'John',
    last: 'Snow'
  },
  title: 'King of the North'
};
            


// Arrays
const nerds = [
  'Sheldon',
  'Leonard',
  'Hovard',
  'Rajesh'
];
            


// Arrays
const wtf = [
  'Sheldon',
  'Leonard',
  'Hovard',
  'Rajesh',
  42,
  {
    name: 'John Snow',
    title: 'King of the North'
  },
  [3, 2, 1]
];
            


// Arrays
nerds.concat
nerds.forEach
nerds.filter
nerds.find
nerds.findIndex
nerds.includes
nerds.join
nerds.map
nerds.push
nerds.pop
nerds.reduce
nerds.shift
nerds.unshift
nerds.slice
nerds.splice
            


// Равентсво (==) и идентичность (===)
123 == '123'
123 === '123'
            


// Равентсво (==) и идентичность (===)
123 == '123'    // true
123 === '123'   // false
            

Замыкания


var functions = [];

for (var i = 0; i < 9; i++) {
    functions[i] = function (a) { return a*i; }
}
            

Замыкания


functions[1](5)
            

45
            


functions[4](4)
            

36
            

Замыкания


functions[5](6)
            

54
            


functions[7](3)
            

27
            

Замыкания


var functions = [];

for (var i = 0; i < 9; i++) {
    (function (b) {
        functions[b]
            = function (a) { return a*b; }
    })(i);
}
            

Замыкания


var functions = [];

for (let i = 0; i < 9; i++) {
    functions[i] = function(a) { return a*i; }
}
            

index.js


const http = require('http');

const server = http.createServer((req, res) => {
  res.end('Hello world!');
});

server.listen(2000, '127.0.0.1', () => {
  console.log('Running');
});
            

index.js


const http = require('http');

const server = http.createServer(handler);

server.listen(2000, '127.0.0.1', () => {
  console.log('Running');
});

function handler(req, res) {
  response.end('Hello world!');
}
            

index.js


const http = require('http');

const server = http.createServer(handler);

server.listen(2000, '127.0.0.1', () => {
  console.log('Running');
});

// так работать не будет
const handler = function (req, res) {
  response.end('Hello world!');
};
            

index.js


function handler(req, res) {
  res.end(req.url);
}
            

index.js


let news = [
  {
    id: 1,
    title: 'Иностранные студенты на практике в БГТУ',
    date: '03.08.16'
  },
  {
    id: 2,
    title: 'День знаний',
    date: '01.09.16'
  }
];
            

index.js


if (req.url === '/') {
  welcome(req, res);
}
else if (req.url === '/news') {
  newsList(req, res);
}
else if (req.url.startsWith('/news?id=')) {
  newsItem(req, res);
}
else if (req.url.startsWith('/news/create')) {
  newsCreate(req, res);
}
    

index.js


else if (req.url.startsWith('/news/update')) {
  newsUpdate(req, res);
}
else if (req.url.startsWith('/news/delete')) {
  newsDelete(req, res);
}
else {
  error404(req, res);
}
            

index.js


function welcome(req, res) {
  res.setHeader('Content-Type', 'text/html');
  res.end('Welcome to our Node.js app');
}
            



index.js


function newsList(req, res) {
  res.setHeader('Content-Type',
    'text/html; charset=utf-8');

  news.forEach((item) => {
    res.write(`[${item.date}] ${item.title}
`); }); res.end(); }




Array.forEach(callback, thisArg)

callback - function (item, index, arr) {}
thisArg - переопределение this
            

const a = ['a', 'b', 'c'];

a.forEach((item, index) => {
  console.log(index, item);
});
            

0 "a"
1 "b"
2 "c"
            

index.js


function newsItem(req, res) {
  res.setHeader('Content-Type',
    'text/html; charset=utf-8');

  const id = req.url.replace('/news?id=', '');
  const item = news.filter(function (item) {
    return item.id == id;
  })[0];

  res.write(`[${item.date}] ${item.title}`);

  res.end();
}
            




Array.filter(callback, thisArg)
            

const a = ['a', 'b', 'c'];

const b = a.filter((item, index) => {
  return index % 2 === 0;
});

b.forEach((item, index) => {
  console.log(index, item);
});
            

0 "a"
1 "c"
            

index.js


function newsCreate(req, res) {
  parseBody(req, (err, params) => {
    const item = {
      id: news.length + 1,
      title: params.title,
      date: params.date
    };

    news.push(item);

    res.end('created');
  });
}
            



index.js


function parseBody(req, cb) {
  let body = [];
  const params = {};

  req.on('data', function(chunk) {
      body.push(chunk);
  }).on('end', function() {
    // был массивом стал строкой
    body = Buffer.concat(body).toString();

    body = body.split('\r\n');
            

index.js


    body = body.filter((item) => {
      return !item.startsWith('------')
        && item !== '';
    });

    for (let i = 0; i < body.length; i += 2) {
      const key = body[i]
        .replace('Content-Disposition: form-data; name="', '')
        .replace('"', '');

      params[key] = body[i + 1];
    }

    cb(null, params);
  });
}
            


body = Buffer.concat(body).toString();
            


------WebKitFormBoundaryN9WJU8ddNCt0tuOa
Content-Disposition: form-data; name="title"

Сенсация
------WebKitFormBoundaryN9WJU8ddNCt0tuOa
Content-Disposition: form-data; name="date"

30.07.2025
------WebKitFormBoundaryN9WJU8ddNCt0tuOa--
            


body = body.split('\r\n');
            


[ '------WebKitFormBoundaryzCDCOBXGeQ1oJkx3',
'Content-Disposition: form-data; name="title"',
'',
'Сенсация',
'------WebKitFormBoundaryzCDCOBXGeQ1oJkx3',
'Content-Disposition: form-data; name="date"',
'',
'30.07.2025',
'------WebKitFormBoundaryzCDCOBXGeQ1oJkx3--',
'' ]
            


body = body.filter((item) => {
  return !item.startsWith('------')
    && item !== '';
});
            


[ 'Content-Disposition: form-data; name="title"',
  'Сенсация',
  'Content-Disposition: form-data; name="date"',
  '30.07.2025' ]
            


for (let i = 0; i < body.length; i += 2) {
  const key = body[i]
    .replace('Content-Disposition: form-data; name="', '')
    .replace('"', '');

  params[key] = body[i + 1];
}
            


{
  title: 'Сенсация',
  date: '30.07.2025'
}
            


function parseBodyJson(req, cb) {
  let body = [];

  req.on('data', function(chunk) {
    body.push(chunk);
  }).on('end', function() {
    body = Buffer.concat(body).toString();

    let params = JSON.parse(body);

    cb(null, params);
  });
}
            


Array.map(callback, thisArg)
            

const a = ['a', 'b', 'c'];

const b = a.map((item) => {
  return item + item;
});

b.forEach((item, index) => {
  console.log(index, item);
});
            

0 "aa"
1 "bb"
2 "cc"
            

index.js


function newsUpdate(req, res) {
  parseBody(req, (err, params) => {
    const item = news.filter((item) => {
      return item.id == params.id;
    })[0];

    item.date = params.date;
    item.title = params.title;

    res.end('updated');
  });
}
            



index.js


function newsDelete(req, res) {
  parseBody(req, (err, params) => {
    news = news.filter((item) => {
      return item.id != params.id;
    });

    res.end('deleted');
  });
}
            



site.css


body {
  color: #ff2c2d;
}
            

index.js


function handler(req, res) {
  ...
  else if (req.url === '/site.css') {
    sendCss(req, res);
  }
  ...
}
            

index.js


const fs = require('fs');

function sendCss(req, res) {
  fs.readFile('site.css', 'utf-8', (err, data) => {
    res.setHeader('Content-Type', 'text/css');
    res.end(data);
  });
}
            


send.js


const fs = require('fs');

function sendCss(req, res) {
  fs.readFile('site.css', 'utf-8', (err, data) => {
    res.setHeader('Content-Type', 'text/css');
    res.end(data);
  });
}

module.exports = {
    css: sendCss
};
            

index.js


const send = require('./send');

...

function handler(req, res) {
  ...
  else if (req.url === '/site.css') {
    send.css(req, res);
  }
  ...
}
            

index.js


function handler(req, res) {
  if (req.url === '/') {
    fs.readFile('index.html', 'utf-8', (err, data) => {
      res.setHeader('Content-Type',
          'text/html; charset=utf-8');

      res.end(data);
    });
  }
  else if (req.url === '/data') {
    res.setHeader('Content-Type',
      'application/json');

    res.end(JSON.stringify(data));
  }
}
            

index.html




Data:

index.html



            

WebStorm - ES6 highlight

WebStorm - Node autocomplete

WebStorm - Startup tasks

WebStorm - Startup tasks

WebStorm - Startup tasks

Какая функция создаёт сервер?
http.createServer

Как функция запускает ожидание запросов?
server.listen

Какой оператор сравнения не приводит типы?
===

Какая функция и у какого объекта позволяет установить заголовок ответа?
res.setHeader

Что нужно сделать что бы ответы корректно распознавались?
Заголовок Content/Type

Что такое замыкания?
Внешние переменные функции

Что делает forEach?
Выполняет действие над элементами массива

Что делает filter?
Выполняет фильтрацию массива

Что делает map?
Выполняет преобразование массива

Как импортировать модуль?
require('имя или путь модуля')