What is Node?

Course Overview

Pure Node.js

The history of Node.js

JavaScript and ES2015

Installation and basics

Less important parts of the API

External services

Node is popular!

  • Server side framework
  • Mobile and IoT
  • Desktop applications
  • Millions of users
  • Largest ecosystem

Node's popularity

This course

  • Intermediate Skills
  • Advanced Skills

What needs to improve?

  • The event-loop
  • V8 and the Call Stack
  • Sockets
  • Event Emitters
  • Streams
  • Clusters

How well do you know Node.js?

This course

Course Path

  • What is Node?
  • npm
  • Concurrency Model and Event Loop
  • Workshop #1
  • Node's Event-driven Architecture
  • Node for Networking
  • Node for Web
  • Node's Common Built-in Libraries
  • Working with Streams
  • Clusters and Child Processes
  • Workshop #2
  • Express.js
  • Real-time Communication with Node.js

  • Testing
  • Workshop #3

  • API Documentation, Automation and Deployment

  • Debugging Node.js In Production

  • Node.js + TypeScript

  • Workshop #4

Architecture:

V8 and libuv

Node VMs

V8

$ node -v
v7.7.4

$ node -p 'process.versions.v8'
5.5.372.42

V8 Feature groups

Shipping

Staged

In progress

--harmony

$ node -p "'Node'.padEnd(8, '*')"
[eval]:1
'Node'.padEnd(8, '*')
       ^

TypeError: "Node".padEnd is not a function
    at [eval]:1:8
    at ContextifyScript.Script.runInThisContext (vm.js:23:33)
    at Object.runInThisContext (vm.js:95:38)
    at Object.<anonymous> ([eval]-wrapper:6:22)
    at Module._compile (module.js:571:32)
    at Immediate.<anonymous> (bootstrap_node.js:392:29)
    at runCallback (timers.js:666:20)
    at tryOnImmediate (timers.js:639:5)
    at processImmediate [as _immediateCallback] (timers.js:611:5)



$ node --harmony -p "'Node'.padEnd(8, '*')"
Node****
$ node --v8-options | grep "in progress"
  --harmony_array_prototype_values (enable "harmony Array.prototype.values" (in progress))
  --harmony_function_sent (enable "harmony function.sent" (in progress))
  --harmony_sharedarraybuffer (enable "harmony sharedarraybuffer" (in progress))
  --harmony_simd (enable "harmony simd" (in progress))
  --harmony_do_expressions (enable "harmony do-expressions" (in progress))
  --harmony_restrictive_generators (enable "harmony restrictions on generator declarations" (in progress))
  --harmony_regexp_named_captures (enable "harmony regexp named captures" (in progress))
  --harmony_regexp_property (enable "harmony unicode regexp property classes" (in progress))
  --harmony_for_in (enable "harmony for-in syntax" (in progress))
  --harmony_trailing_commas (enable "harmony trailing commas in function parameter lists" (in progress))
  --harmony_class_fields (enable "harmony public fields in class literals" (in progress))

Node’s CLI and REPL

Read

Eval

Print

Loop

node
> 3 == '3'
true
> var a = 2
undefined
>
>
Array                                Boolean                              Date                                 Error
EvalError                            Function                             Infinity                             JSON
Math                                 NaN                                  Number                               Object
RangeError                           ReferenceError                       RegExp                               String
SyntaxError                          TypeError                            URIError                             decodeURI
decodeURIComponent                   encodeURI                            encodeURIComponent                   eval
isFinite                             isNaN                                parseFloat                           parseInt
undefined                            

ArrayBuffer                          Buffer                               COUNTER_HTTP_CLIENT_REQUEST          COUNTER_HTTP_CLIENT_RESPONSE
COUNTER_HTTP_SERVER_REQUEST          COUNTER_HTTP_SERVER_RESPONSE         COUNTER_NET_SERVER_CONNECTION        COUNTER_NET_SERVER_CONNECTION_CLOSE
DTRACE_HTTP_CLIENT_REQUEST           DTRACE_HTTP_CLIENT_RESPONSE          DTRACE_HTTP_SERVER_REQUEST           DTRACE_HTTP_SERVER_RESPONSE
DTRACE_NET_SERVER_CONNECTION         DTRACE_NET_STREAM_END                DataView                             Float32Array
Float64Array                         GLOBAL                               Int16Array                           Int32Array
Int8Array                            Intl                                 Map                                  Promise
Proxy                                Reflect                              Set                                  Symbol
Uint16Array                          Uint32Array                          Uint8Array                           Uint8ClampedArray
WeakMap                              WeakSet                              _                                    a
assert                               buffer                               child_process                        clearImmediate
clearInterval                        clearTimeout                         cluster                              console
crypto                               dgram                                dns                                  domain
escape                               events                               fs                                   global
http                                 https                                module                               net
os                                   path                                 process                              punycode
querystring                          readline                             repl                                 require
root                                 setImmediate                         setInterval                          setTimeout
stream                               string_decoder                       tls                                  tty
unescape                             url                                  util                                 v8
vm                                   zlib                                 

__defineGetter__                     __defineSetter__                     __lookupGetter__                     __lookupSetter__
__proto__                            constructor                          hasOwnProperty                       isPrototypeOf
propertyIsEnumerable                 toLocaleString                       toString                             valueOf

>

Autocomplete - Double TAB

> global.
global.__defineGetter__                     global.__defineSetter__                     global.__lookupGetter__                     global.__lookupSetter__
global.__proto__                            global.constructor                          global.hasOwnProperty                       global.isPrototypeOf
global.propertyIsEnumerable                 global.toLocaleString                       global.toString                             global.valueOf

global.Array                                global.ArrayBuffer                          global.Boolean                              global.Buffer
global.COUNTER_HTTP_CLIENT_REQUEST          global.COUNTER_HTTP_CLIENT_RESPONSE         global.COUNTER_HTTP_SERVER_REQUEST          global.COUNTER_HTTP_SERVER_RESPONSE
global.COUNTER_NET_SERVER_CONNECTION        global.COUNTER_NET_SERVER_CONNECTION_CLOSE  global.DTRACE_HTTP_CLIENT_REQUEST           global.DTRACE_HTTP_CLIENT_RESPONSE
global.DTRACE_HTTP_SERVER_REQUEST           global.DTRACE_HTTP_SERVER_RESPONSE          global.DTRACE_NET_SERVER_CONNECTION         global.DTRACE_NET_STREAM_END
global.DataView                             global.Date                                 global.Error                                global.EvalError
global.Float32Array                         global.Float64Array                         global.Function                             global.GLOBAL
global.Infinity                             global.Int16Array                           global.Int32Array                           global.Int8Array
global.Intl                                 global.JSON                                 global.Map                                  global.Math
global.NaN                                  global.Number                               global.Object                               global.Promise
global.Proxy                                global.RangeError                           global.ReferenceError                       global.Reflect
global.RegExp                               global.Set                                  global.String                               global.Symbol
global.SyntaxError                          global.TypeError                            global.URIError                             global.Uint16Array
global.Uint32Array                          global.Uint8Array                           global.Uint8ClampedArray                    global.WeakMap
global.WeakSet                              global._                                    global.a                                    global.assert
global.buffer                               global.child_process                        global.clearImmediate                       global.clearInterval
global.clearTimeout                         global.cluster                              global.console                              global.crypto
global.decodeURI                            global.decodeURIComponent                   global.dgram                                global.dns
global.domain                               global.encodeURI                            global.encodeURIComponent                   global.escape
global.eval                                 global.events                               global.fs                                   global.global
global.http                                 global.https                                global.isFinite                             global.isNaN
global.module                               global.net                                  global.os                                   global.parseFloat
global.parseInt                             global.path                                 global.process                              global.punycode
global.querystring                          global.readline                             global.repl                                 global.require
global.root                                 global.setImmediate                         global.setInterval                          global.setTimeout
global.stream                               global.string_decoder                       global.tls                                  global.tty
global.undefined                            global.unescape                             global.url                                  global.util
global.v8                                   global.vm                                   global.zlib                                 

> global.

Autocomplete - Double TAB

> var arr =[];
undefined
> arr.
arr.__defineGetter__      arr.__defineSetter__      arr.__lookupGetter__      arr.__lookupSetter__      arr.__proto__             arr.constructor           arr.hasOwnProperty
arr.isPrototypeOf         arr.propertyIsEnumerable  arr.toLocaleString        arr.toString              arr.valueOf               

arr.concat                arr.copyWithin            arr.entries               arr.every                 arr.fill                  arr.filter                arr.find
arr.findIndex             arr.forEach               arr.includes              arr.indexOf               arr.join                  arr.keys                  arr.lastIndexOf
arr.length                arr.map                   arr.pop                   arr.push                  arr.reduce                arr.reduceRight           arr.reverse
arr.shift                 arr.slice                 arr.some                  arr.sort                  arr.splice                arr.unshift               

> arr.

Autocomplete - Double TAB

> _
undefined
> Math.random()
0.34758947986306477
> _
0.34758947986306477
> let r = _
undefined
> r
0.34758947986306477
>

The last result - Underscore

> .
break   clear   editor  exit    help    load    save    

> .help
.break    Sometimes you get stuck, this gets you out
.clear    Alias for .break
.editor   Enter editor mode
.exit     Exit the repl
.help     Print this help message
.load     Load JS from a file into the REPL session
.save     Save all evaluated commands in this REPL session to a file

Special commands - Dot

const repl = require('repl');

repl.start({
    ignoreUndefined: true,
    replMode: repl.REPL_MODE_STRICT
});

Customize REPL

Customize REPL

Global Objects, Process and Buffer

Array                                Boolean                              Date                                 Error
EvalError                            Function                             Infinity                             JSON
Math                                 NaN                                  Number                               Object
RangeError                           ReferenceError                       RegExp                               String
SyntaxError                          TypeError                            URIError                             decodeURI
decodeURIComponent                   encodeURI                            encodeURIComponent                   eval
isFinite                             isNaN                                parseFloat                           parseInt
undefined

ArrayBuffer                          Buffer                               COUNTER_HTTP_CLIENT_REQUEST          COUNTER_HTTP_CLIENT_RESPONSE
COUNTER_HTTP_SERVER_REQUEST          COUNTER_HTTP_SERVER_RESPONSE         COUNTER_NET_SERVER_CONNECTION        COUNTER_NET_SERVER_CONNECTION_CLOSE
DTRACE_HTTP_CLIENT_REQUEST           DTRACE_HTTP_CLIENT_RESPONSE          DTRACE_HTTP_SERVER_REQUEST           DTRACE_HTTP_SERVER_RESPONSE
DTRACE_NET_SERVER_CONNECTION         DTRACE_NET_STREAM_END                DataView                             Float32Array
Float64Array                         GLOBAL                               Int16Array                           Int32Array
Int8Array                            Intl                                 Map                                  Promise
Proxy                                Reflect                              Set                                  Symbol
Uint16Array                          Uint32Array                          Uint8Array                           Uint8ClampedArray
WeakMap                              WeakSet                              _                                    assert
buffer                               child_process                        clearImmediate                       clearInterval
clearTimeout                         cluster                              console                              crypto
dgram                                dns                                  domain                               escape
events                               fs                                   global                               http
https                                module                               net                                  os
path                                 process                              punycode                             querystring
readline                             repl                                 require                              root
setImmediate                         setInterval                          setTimeout                           stream
string_decoder                       tls                                  tty                                  unescape
url                                  util                                 v8                                   vm
zlib

__defineGetter__                     __defineSetter__                     __lookupGetter__                     __lookupSetter__
__proto__                            constructor                          hasOwnProperty                       isPrototypeOf
propertyIsEnumerable                 toLocaleString                       toString                             valueOf
console.log(global);

{ DTRACE_NET_SERVER_CONNECTION: [Function],
  DTRACE_NET_STREAM_END: [Function],
  DTRACE_HTTP_SERVER_REQUEST: [Function],
  DTRACE_HTTP_SERVER_RESPONSE: [Function],
  DTRACE_HTTP_CLIENT_REQUEST: [Function],
  DTRACE_HTTP_CLIENT_RESPONSE: [Function],
  COUNTER_NET_SERVER_CONNECTION: [Function],
  COUNTER_NET_SERVER_CONNECTION_CLOSE: [Function],
  COUNTER_HTTP_SERVER_REQUEST: [Function],
  COUNTER_HTTP_SERVER_RESPONSE: [Function],
  COUNTER_HTTP_CLIENT_REQUEST: [Function],
  COUNTER_HTTP_CLIENT_RESPONSE: [Function],
  global: [Circular],
  process: 
   process {
     title: 'C:\\Program Files (x86)\\JetBrains\\WebStorm 2017.1\\bin\\runnerw.exe',
     version: 'v7.7.4',
     moduleLoadList: 
      [ 'Binding contextify',
        'Binding natives',
        'NativeModule events',
        'Binding config',
        'Binding icu',
        'NativeModule util',
        'Binding uv',
        'NativeModule buffer',
        'Binding buffer',
        'Binding util',
        'NativeModule internal/util',
        'NativeModule internal/buffer',
        'NativeModule timers',
        'Binding timer_wrap',
        'NativeModule internal/linkedlist',
        'NativeModule assert',
        'NativeModule internal/process',
        'NativeModule internal/process/warning',
        'NativeModule internal/process/next_tick',
        'NativeModule internal/process/promises',
        'NativeModule internal/process/stdio',
        'Binding constants',
        'NativeModule path',
        'NativeModule module',
        'NativeModule internal/module',
        'NativeModule vm',
        'NativeModule fs',
        'Binding fs',
        'NativeModule stream',
        'NativeModule internal/streams/legacy',
        'NativeModule _stream_readable',
        'NativeModule internal/streams/BufferList',
        'NativeModule _stream_writable',
        'NativeModule _stream_duplex',
        'NativeModule _stream_transform',
        'NativeModule _stream_passthrough',
        'Binding fs_event_wrap',
        'NativeModule internal/fs',
        'NativeModule internal/url',
        'NativeModule internal/querystring',
        'Binding url',
        'NativeModule querystring',
        'NativeModule os',
        'Binding os',
        'NativeModule console',
        'Binding tty_wrap',
        'NativeModule net',
        'NativeModule internal/net',
        'Binding cares_wrap',
        'Binding tcp_wrap',
        'Binding pipe_wrap',
        'Binding stream_wrap' ],
     versions: 
      { http_parser: '2.7.0',
        node: '7.7.4',
        v8: '5.5.372.42',
        uv: '1.11.0',
        zlib: '1.2.11',
        ares: '1.10.1-DEV',
        modules: '51',
        openssl: '1.0.2k',
        icu: '58.2',
        unicode: '9.0',
        cldr: '30.0.3',
        tz: '2016j' },
     arch: 'x64',
     platform: 'win32',
     release: 
      { name: 'node',
        sourceUrl: 'https://nodejs.org/download/release/v7.7.4/node-v7.7.4.tar.gz',
        headersUrl: 'https://nodejs.org/download/release/v7.7.4/node-v7.7.4-headers.tar.gz',
        libUrl: 'https://nodejs.org/download/release/v7.7.4/win-x64/node.lib' },
     argv: 
      [ 'C:\\Program Files\\nodejs\\node.exe',
        'D:\\projects\\nodejs-training\\module-1\\require\\index2.js' ],
     execArgv: [],
     env: 
      { ALLUSERSPROFILE: 'C:\\ProgramData',
        APPDATA: 'C:\\Users\\Shukhratbek_Mamadali\\AppData\\Roaming',
        CommonProgramFiles: 'C:\\Program Files\\Common Files',
        'CommonProgramFiles(x86)': 'C:\\Program Files (x86)\\Common Files',
        CommonProgramW6432: 'C:\\Program Files\\Common Files',
        COMPUTERNAME: 'EPBYGOMW0515',
        ComSpec: 'C:\\WINDOWS\\system32\\cmd.exe',
        DEBUG_COLORS: 'true',
        DEBUG_FD: '1',
        ELECTRON_NO_ATTACH_CONSOLE: 'true',
        FORCE_COLOR: 'true',
        FPS_BROWSER_APP_PROFILE_STRING: 'Internet Explorer',
        FPS_BROWSER_USER_PROFILE_STRING: 'Default',
        GIT_SSH: 'C:\\Program Files\\PuTTY\\plink.exe',
        GYP_MSVS_VERSION: '2015',
        HOMEDRIVE: 'C:',
        HOMEPATH: '\\Users\\Shukhratbek_Mamadali',
        LOCALAPPDATA: 'C:\\Users\\Shukhratbek_Mamadali\\AppData\\Local',
        LOGONSERVER: '\\\\EVBYGOMSA0003',
        MOCHA_COLORS: '1',
        NUMBER_OF_PROCESSORS: '4',
        OneDrive: 'C:\\Users\\Shukhratbek_Mamadali\\OneDrive',
        OS: 'Windows_NT',
        Path: 'C:\\Program Files\\Docker\\Docker\\Resources\\bin;C:\\WINDOWS\\system32;C:\\WINDOWS;C:\\WINDOWS\\System32\\Wbem;C:\\WINDOWS\\System32\\WindowsPowerShell\\v1.0\\;C:\\Program Files\\Git\\cmd;C:\\Program Files\\PuTTY\\;C:\\Program Files\\nodejs\\;C:\\Program Files\\OpenVPN\\bin;C:\\HashiCorp\\Vagrant\\bin;C:\\Program Files (x86)\\Windows Kits\\8.1\\Windows Performance Toolkit\\;C:\\Ruby23-x64\\bin;C:\\Users\\Shukhratbek_Mamadali\\AppData\\Local\\Microsoft\\WindowsApps;C:\\Users\\Shukhratbek_Mamadali\\AppData\\Roaming\\npm',
        PATHEXT: '.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC;.RB;.RBW',
        PROCESSOR_ARCHITECTURE: 'AMD64',
        PROCESSOR_IDENTIFIER: 'Intel64 Family 6 Model 78 Stepping 3, GenuineIntel',
        PROCESSOR_LEVEL: '6',
        PROCESSOR_REVISION: '4e03',
        ProgramData: 'C:\\ProgramData',
        ProgramFiles: 'C:\\Program Files',
        'ProgramFiles(x86)': 'C:\\Program Files (x86)',
        ProgramW6432: 'C:\\Program Files',
        PSModulePath: 'C:\\Program Files\\WindowsPowerShell\\Modules;C:\\WINDOWS\\system32\\WindowsPowerShell\\v1.0\\Modules',
        PUBLIC: 'C:\\Users\\Public',
        SESSIONNAME: 'Console',
        SSL_CERT_FILE: 'C:\\RailsInstaller\\cacert.pem',
        SYNDICATION_CONF: 'config/properties.json',
        SystemDrive: 'C:',
        SystemRoot: 'C:\\WINDOWS',
        TEMP: 'C:\\Users\\SHUKHR~1\\AppData\\Local\\Temp',
        TMP: 'C:\\Users\\SHUKHR~1\\AppData\\Local\\Temp',
        UATDATA: 'C:\\WINDOWS\\CCM\\UATData\\D9F8C395-CAB8-491d-B8AC-179A1FE1BE77',
        USERDNSDOMAIN: 'GOMEL.EPAM.COM',
        USERDOMAIN: 'GOMEL',
        USERDOMAIN_ROAMINGPROFILE: 'GOMEL',
        USERNAME: 'Shukhratbek_Mamadali',
        USERPROFILE: 'C:\\Users\\Shukhratbek_Mamadali',
        VBOX_MSI_INSTALL_PATH: 'C:\\Program Files\\Oracle\\VirtualBox\\',
        VS140COMNTOOLS: 'C:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\Common7\\Tools\\',
        WEB_CONCURRENCY: 'cluster.js',
        windir: 'C:\\WINDOWS' },
     pid: 800,
     features: 
      { debug: false,
        uv: true,
        ipv6: true,
        tls_npn: true,
        tls_alpn: true,
        tls_sni: true,
        tls_ocsp: true,
        tls: true },
     _needImmediateCallback: false,
     execPath: 'C:\\Program Files\\nodejs\\node.exe',
     debugPort: 5858,
     _startProfilerIdleNotifier: [Function: _startProfilerIdleNotifier],
     _stopProfilerIdleNotifier: [Function: _stopProfilerIdleNotifier],
     _getActiveRequests: [Function: _getActiveRequests],
     _getActiveHandles: [Function: _getActiveHandles],
     reallyExit: [Function: reallyExit],
     abort: [Function: abort],
     chdir: [Function: chdir],
     cwd: [Function: cwd],
     umask: [Function: umask],
     _kill: [Function: _kill],
     _debugProcess: [Function: _debugProcess],
     _debugPause: [Function: _debugPause],
     _debugEnd: [Function: _debugEnd],
     hrtime: [Function: hrtime],
     cpuUsage: [Function: cpuUsage],
     dlopen: [Function: dlopen],
     uptime: [Function: uptime],
     memoryUsage: [Function: memoryUsage],
     binding: [Function: binding],
     _linkedBinding: [Function: _linkedBinding],
     _setupDomainUse: [Function: _setupDomainUse],
     _events: 
      { warning: [Function],
        newListener: [Function],
        removeListener: [Function] },
     _rawDebug: [Function],
     _eventsCount: 3,
     domain: null,
     _maxListeners: undefined,
     _fatalException: [Function],
     _exiting: false,
     assert: [Function],
     config: { target_defaults: [Object], variables: [Object] },
     emitWarning: [Function],
     nextTick: [Function: nextTick],
     _tickCallback: [Function: _tickCallback],
     _tickDomainCallback: [Function: _tickDomainCallback],
     stdout: [Getter],
     stderr: [Getter],
     stdin: [Getter],
     openStdin: [Function],
     exit: [Function],
     kill: [Function],
     argv0: 'C:\\Program Files\\nodejs\\node.exe',
     mainModule: 
      Module {
        id: '.',
        exports: {},
        parent: null,
        filename: 'D:\\projects\\nodejs-training\\module-1\\require\\index2.js',
        loaded: false,
        children: [],
        paths: [Object] } },
  Buffer: 
   { [Function: Buffer]
     poolSize: 8192,
     from: [Function],
     alloc: [Function],
     allocUnsafe: [Function],
     allocUnsafeSlow: [Function],
     isBuffer: [Function: isBuffer],
     compare: [Function: compare],
     isEncoding: [Function],
     concat: [Function],
     byteLength: [Function: byteLength] },
  clearImmediate: [Function],
  clearInterval: [Function],
  clearTimeout: [Function],
  setImmediate: [Function],
  setInterval: [Function],
  setTimeout: [Function],
  console: [Getter] }
process.versions
process.versions.v8
process.env
process.release.lts
process.stdin
process.stdout
 buffer
{ Buffer:
   { [Function: Buffer]
     poolSize: 8192,
     from: [Function],
     alloc: [Function],
     allocUnsafe: [Function],
     allocUnsafeSlow: [Function],
     isBuffer: [Function: isBuffer],
     compare: [Function: compare],
     isEncoding: [Function],
     concat: [Function],
     byteLength: [Function: byteLength] },
  SlowBuffer: [Function: SlowBuffer],
  INSPECT_MAX_BYTES: 50,
  kMaxLength: 2147483647,
  transcode: [Function: transcode] }

require()

require("module")

require("something")

console.log(module);

Module {
  id: '.',
  exports: {},
  parent: null,
  filename: 'D:\\projects\\nodejs-training\\module-1\\require\\index.js',
  loaded: false,
  children: [],
  paths: 
   [ 'D:\\projects\\nodejs-training\\module-1\\require\\node_modules',
     'D:\\projects\\nodejs-training\\module-1\\node_modules',
     'D:\\projects\\nodejs-training\\node_modules',
     'D:\\projects\\node_modules',
     'D:\\node_modules' ] }
require('find-me');

module.js:472
    throw err;
    ^

Error: Cannot find module 'find-me'
    at Function.Module._resolveFilename (module.js:470:15)
    at Function.Module._load (module.js:418:25)
    at Module.require (module.js:498:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (D:\projects\nodejs-training\module-1\require\index.js:1:63)
    at Module._compile (module.js:571:32)
    at Object.Module._extensions..js (module.js:580:10)
    at Module.load (module.js:488:32)
    at tryModuleLoad (module.js:447:12)
    at Function.Module._load (module.js:439:3)
// $HOME/.node_modules
// $HOME/.node_libraries
// $PREFIX/lib/node
// index.js

console.log('In ./index.js');

require('find-me');
// ./node_modules/find-me.js

console.log('In ./node_modules/find-me.js');
// Terminal

In ./index.js
In ./node_modules/find-me.js
require.resolve('find-me');
loaded: false
m1 is not loaded yet { id: 'm1', content: [ 1 ] }
{ id: 'm2', content: [ 2, 22, 222 ] }
{ id: 'm1', content: [ 1, 11, 111 ] }
// m1.js

exports.id = 'm1';

exports.content = [1];
const m2 = require('./m2');
console.log(m2);

exports.content.push(11);
exports.content.push(111);
// m2.js

exports.id = 'm2';

exports.content = [2];
exports.content.push(22);
exports.content.push(222);

const m1 = require('./m1');
console.log('m1 is not loaded yet', m1);
// index.js

const m1 = require('./lib/m1');
console.log(m1);

Wrapping and Caching Modules

exports.id = 1; // this is ok

exports = {id: 1}; // this is not ok

module.exports = {id: 1}; // this is ok


var g = 42; // local to this file
node

require('module').wrapper
[ '(function (exports, require, module, __filename, __dirname) { ',
  '\n});' ]
console.log(arguments);
{ '0': {},
  '1': 
   { [Function: require]
     resolve: [Function: resolve],
     main: 
      Module {
        id: '.',
        exports: {},
        parent: null,
        filename: 'D:\\projects\\nodejs-training\\module-1\\wrapper.js',
        loaded: false,
        children: [],
        paths: [Object] },
     extensions: { '.js': [Function], '.json': [Function], '.node': [Function] },
     cache: { 'D:\projects\nodejs-training\module-1\wrapper.js': [Object] } },
  '2': 
   Module {
     id: '.',
     exports: {},
     parent: null,
     filename: 'D:\\projects\\nodejs-training\\module-1\\wrapper.js',
     loaded: false,
     children: [],
     paths: 
      [ 'D:\\projects\\nodejs-training\\module-1\\node_modules',
        'D:\\projects\\nodejs-training\\node_modules',
        'D:\\projects\\node_modules',
        'D:\\node_modules' ] },
  '3': 'D:\\projects\\nodejs-training\\module-1\\wrapper.js',
  '4': 'D:\\projects\\nodejs-training\\module-1' }
require = function() {
    return { mocked: true};
};

const fs = require('fs');
console.log(fs);

Override require

// printStars.js

const print = (stars, header) => {
    console.log('*'.repeat(stars));
    console.log(header);
    console.log('*'.repeat(stars));
};

if (require.main == module) {
    // Running as script

    print(process.argv[2], process.argv[3]);
} else {
    // Being required
    module.exports = print;
}
// index.js

const printStars = require('./printStars');
printStars(10, 'Hi!');
// index.js

require('./sample');
require('./sample');

Caching

// sample.js

console.log(`
    Sample
    File
`);
console.log(require.cache);

Caching


    Sample
    File

{ 'D:\projects\nodejs-training\module-1\wrapper\index.js': 
   Module {
     id: '.',
     exports: {},
     parent: null,
     filename: 'D:\\projects\\nodejs-training\\module-1\\wrapper\\index.js',
     loaded: false,
     children: [ [Object] ],
     paths: 
      [ 'D:\\projects\\nodejs-training\\module-1\\wrapper\\node_modules',
        'D:\\projects\\nodejs-training\\module-1\\node_modules',
        'D:\\projects\\nodejs-training\\node_modules',
        'D:\\projects\\node_modules',
        'D:\\node_modules' ] },
  'D:\projects\nodejs-training\module-1\wrapper\sample.js': 
   Module {
     id: 'D:\\projects\\nodejs-training\\module-1\\wrapper\\sample.js',
     exports: {},
     parent: 
      Module {
        id: '.',
        exports: {},
        parent: null,
        filename: 'D:\\projects\\nodejs-training\\module-1\\wrapper\\index.js',
        loaded: false,
        children: [Object],
        paths: [Object] },
     filename: 'D:\\projects\\nodejs-training\\module-1\\wrapper\\sample.js',
     loaded: true,
     children: [],
     paths: 
      [ 'D:\\projects\\nodejs-training\\module-1\\wrapper\\node_modules',
        'D:\\projects\\nodejs-training\\module-1\\node_modules',
        'D:\\projects\\nodejs-training\\node_modules',
        'D:\\projects\\node_modules',
        'D:\\node_modules' ] } }
delete require.cache['D:\projects\nodejs-training\module-1\wrapper\sampls.js'];

Delete Cache

// sample.js

module.exports = () => {
    console.log(`
        Sample
        File
    `);
};

Module multiple execute

// index.js

require('./sample')();
require('./sample')();

Hello World!

What is Node?

By Shuhratbek Mamadaliyev

What is Node?

  • 1,092