вторник, 7 февраля 2017 г.

Node.js - Функции

Оглавление:

- command line options - --version,  --help and run file.js
- debugger - debug, --inspect
- modules - require, exports
- global - variables and functions
- console - log, error, warn, time, timeEnd, Console
- util - inspect, format, _extend
- assert - ok, deepEqual
- timers - setImmediate, setTimeout, setInterval
- error - throw new Error(), captureStackTrace
- domain - async errors
- v8 - getHeapStatistics, getHeapSpaceStatistics, setFlagsFromString
- os - uptime, cpus, totalmem, homedir, networkInterfaces
- process - nextTick, argv, cwd, stdin, stdout, stderr
- child_process - execFile, exec, spawn, fork
- cluster - isMaster, isWorker, fork
- vm - eval script
- repl - prompt
- readline - prompt and question
- tty - text terminal resize, columns, rows
- events - addListener, prependListener, removeLitener, on, once, emit
- path - dirname, basename, parse, format, join, resolve
- fs - mkdir, readdir, rmdir, stat, open, read, write, close, writeFile, appendFile, rename, unlink
- zlib - createGzip, createGunzip, createDeflate, unzip
- crypto - createCipher, createDecipher, createDiffieHellman, computeSecret, createHash
- punycode - encode, decode, toASCII, toUnicode
- stream - Readable, Writable, Duplex, Transform, createReadStream, createWriteStream
- buffer - alloc, from, concat, length, byteLength, keys, values, entries
- string_decoder - write, end
url - parse, format, resolve
querystring - parse, stringify, escape, unescape
- dns - lookup, lookupService, resolve4
- http, https - Agent, get, request, createServer
- net - Socket, connect, createConnection, createServer
- tls - TLSSocket, connect, createServer, Server
- dgram - createSocket

HTTP server
HTTP client
TCP Socket server
TCP Socket client
UDP server
UDP client

command line options - --version,  --help and run file.js

node.exe
node.exe --version
node.exe --help
node.exe debug server.js
node.exe server.js
node.exe gulp.js build

debugger - debug, --inspect

node --inspect index.js
Debugger listening on port 9229.
Warning: This is an experimental feature and could change at any time.
To start debugging, open the following URL in Chrome:
    chrome-devtools://devtools/remote/serve_file/@60cd6e859b9f557d2312f5bf532f6aec5f284980/inspector.html?experiments=true&v8only=true&ws=localhost:9229/node

//---------------------------------------------

node debug myscript.js
< debugger listening on port 5858
connecting... ok
break in /home/indutny/Code/git/indutny/myscript.js:1
  1 x = 5;
  2 setTimeout(() => {
  3   debugger;
debug> cont
< hello
break in /home/indutny/Code/git/indutny/myscript.js:3
  1 x = 5;
  2 setTimeout(() => {
  3   debugger;
  4   console.log('world');
  5 }, 1000);
debug> next
break in /home/indutny/Code/git/indutny/myscript.js:4
  2 setTimeout(() => {
  3   debugger;
  4   console.log('world');
  5 }, 1000);
  6 console.log('hello');
debug> repl
Press Ctrl + C to leave debug repl
> x
5
> 2+2
4
debug> next
< world
break in /home/indutny/Code/git/indutny/myscript.js:5
  3   debugger;
  4   console.log('world');
  5 }, 1000);
  6 console.log('hello');
  7
debug> quit

modules - require, exports

(function (exports, require, module, __filename, __dirname) {
    // Your module code actually lives in here
});

//---------------------------------------------

function require (...) {
    var module = {exports: {}};
    (function (module, exports) {
        // Your module code here. In this example, define a function.
        function some_func() {};
        exports = some_func;
        // At this point, exports is no longer a shortcut to module.exports, and
        // this module will still export an empty default object.
        module.exports = some_func;
        // At this point, the module will now export some_func, instead of the
        // default object.
    })(module, module.exports);
    return module.exports;
}

//---------------------------------------------

if (require.main === module) {
    console.log('This file is run directly from Node.js: node foo.js');
} else {
    console.log('This file is run by: var server = require("./server.js");');
}

//---------------------------------------------

module.exports = exports = function Constructor() {};
module.exports.hello = true; // Exported from require of module
exports = {hello: false};  // Not exported, only available in the module

module.exports = function (width) {
    return {
        area: function () {return width * width}
    };
}

exports.area = function (r) {return Math.PI * r * r;}

//---------------------------------------------

var someModule = module.require('./../path/to/file.js');

var circle = require('./circle.js');
console.log('The area of a circle of radius 4 is ' + circle.area(4));

//---------------------------------------------

if (module.loaded) {}

//---------------------------------------------

console.log(module);
console.log(module.parent);
console.log(module.children);
console.log(module.filename); // module filename
console.log(module.id); // module filename

global - variables and functions

var someModule = require('./../some/folder/script.js');
console.log(require.cache);
console.log(require.resolve('./../some/folder/script.js')); // script.js
require.extensions['.sjs'] = require.extensions['.js'];

exports = module.exports;
exports.someVar = 1;

module.exports.someVar = 1;

console.log();

console.log(__dirname);
console.log(__filename);
console.log(path.dirname(__filename));

global.someVar = 1;

var buf = Buffer.from([1, 2, 3]);

var immediateId = setImmediate(function () {}, ...args);
var timeoutId = setTimeout(function () {}, 5000, ...args);
var intevalId = setInterval(function () {}, 5000, ...args);

clearImmediate(immediateId);
clearTimeout(timeoutId);
clearInterval(intevalId);

process.on('exit', function ('code') {console.log('exited with code: ' + code);});

console - log, error, warn, time, timeEnd, Console

var Console = require('console').Console;

// var myConsole = new console.Console(stdoutStream,  stderrStream);
// var myConsole = new Console(process.stdout, process.stderr);
var myConsole = new Console(
       fs.createWriteStream('./stdout.log')
    ,  fs.createWriteStream('./stderr.log')
);
myConsole.log('hello %s', 'world');
myConsole.warn('Danger! Danger!');
myConsole.error(new Error('Whoops, something bad happened'));

//---------------------------------------------

console.log('count:', 5);
console.log('hello %s', 'world'); // console.info('hello %s', 'world');
console.warn('Danger! Danger!');
console.error(new Error('Whoops, something bad happened')); // console.error('error #%d', 5);

console.trace('Show me stack trace');

console.dir({a: 1, b: 2}, {showHidden: true, depth: 2});

console.assert(false, 'Whoops %s', 'didn\'t work');

console.time('100-elements');
console.timeEnd('100-elements');

util - inspect, format, _extend

var util = require('util');

//---------------------------------------------

var debuglog = util.debuglog('foo');
debuglog('hello from foo [%d]', 123); // FOO 3245: hello from foo [123]

//---------------------------------------------

util.log('Timestamped message.');

//---------------------------------------------

console.log(util.inspect({a: 1}, {showHidden: true, depth: null}));

var obj = {foo: 'this will not show up in the inspect() output'};
obj[util.inspect.custom] = function(depth) {return {bar: 'baz'};};
console.log(util.inspect(obj)); // "{ bar: 'baz' }"

//---------------------------------------------

var util = require('util');

var arr = Array(101);

console.log(arr); // logs the truncated array
util.inspect.defaultOptions.maxArrayLength = null;
console.log(arr); // logs the full array

//---------------------------------------------

exports.puts = util.deprecate(function () {
    for (var i = 0, len = arguments.length; i < len; i++) {
        process.stdout.write(arguments[i] + '\n');
    }
}, 'util.puts: Use console.log instead');

//---------------------------------------------

util.format('%s:%d:%j%%', 'foo', 123, {a: 1}); // 'foo:123:{"a":1}%'

//---------------------------------------------

util._extend({a: 1}, {b: 2}); // --> Object.assign(target, source);

//---------------------------------------------

function MyStreamClass () {
    EventEmitter.call(this);
}

util.inherits(MyStreamClass, EventEmitter);

MyStream.prototype.write = function(data) {
    this.emit('data', data);
};

console.log(MyStream.super_ === EventEmitter); // true

//---------------------------------------------

// Deprecated

if (util.isArray([])) {}
if (util.isBoolean(true)) {}
if (util.isBuffer(Buffer.from('hello world'))) {}
if (util.isDate(new Date())) {}
if (util.isError(new Error())) {}
if (util.isFunction(Foo)) {}
if (util.isNull(null)) {}
if (util.isNullOrUndefined(undefined)) {}
if (util.isNumber(Infinity)) {}
if (util.isObject({})) {}
if (util.isPrimitive('foo')) {}
if (util.isRegExp(/some regexp/)) {}
if (util.isString('')) {}
if (util.isSymbol(Symbol('foo'))) {}
if (util.isUndefined(foo)) {}

//---------------------------------------------

util.debug('string'); // --> console.error('string');
util.error(...'strings'); // --> console.error(...'strings');

util.print(...'strings'); // --> console.log(...'strings');
util.puts(...'strings'); // --> console.log(...'strings');

assert - ok, deepEqual

var assert = require('assert');

assert(false, 'Error message');
assert.ok(false, 'Error message');
assert.fail(1, 2, undefined, '>'); // AssertionError: 1 > 2
assert.strictEqual(1, '1', 'Error message');
assert.deepEqual({a: 1}, {b: 2}, 'Error message');

timers - setImmediate, setTimeout, setInterval

var immediateId = setImmediate(function () {}, ...args);
var timeoutId = setTimeout(function () {}, 5000, ...args);
var intervalId = setInterval(function () {}, 5000, ...args);

clearImmediate(immediateId);
clearTimeout(timeoutId);
clearInterval(intervalId);

timeoutId.ref();
timeoutId.unref();

error - throw new Error(), captureStackTrace

const error = new Error('The message');
console.log(error.message);

//---------------------------------------------

try {
    var m = 1 + z;
} catch (error) {
    // Handle the error here.
}

//---------------------------------------------

var fs = require('fs');
fs.readFile('a file that does not exist', function (error, data) {
    if (error) {
        console.error('There was an error reading the file!', error);
        return;
    }
    // Otherwise handle the data
});

//---------------------------------------------

var EventEmitter = require('events');
var ee = new EventEmitter();

setImmediate(function () {
    ee.emit('error', new Error('This will crash'));
});

//---------------------------------------------

var myObject = {};
Error.captureStackTrace(myObject);
console.log(myObject.stack); // similar to "new Error().stack"

//---------------------------------------------

function MyError() {
    Error.captureStackTrace(this, MyError);
}
console.log(new MyError().stack);

//---------------------------------------------

require('net').connect(-1); // throws RangeError, port should be > 0 && < 65536

doesNotExist; // throws ReferenceError, doesNotExist is not a variable in this program.

require('url').parse(function () { }); // throws TypeError, since it expected a string

try {
    require('vm').runInThisContext('binary ! isNotOk');
} catch (error) {
    // error will be a SyntaxError
}

domain - async errors

var domain = require('domain');
var fs = require('fs');

var d = domain.create();
d.on('error', function (error) {console.error('Caught error!', error);});
d.run(function () {
    process.nextTick(function () {
        setTimeout(function () {
            fs.open('non-existent file', 'r', function (error, fd) {
                if (error) {throw error;}
                // proceed...
            });
        }, 100);
    });
});

//---------------------------------------------

var domain = require('domain');
var http = require('http');

var serverDomain = domain.create();

serverDomain.run(function () {
    http.createServer(function (request, response) {
        var reqd = domain.create();
        reqd.add(request);
        reqd.add(response);
        reqd.on('error', function (error) {
            console.error('Error', error, request.url);
            try {
                response.writeHead(500);
                response.end('Error occurred, sorry.');
            } catch (error2) {
                console.error('Error sending 500', error2, request.url);
            }
        });
    }).listen(1337);
});

//---------------------------------------------

var d = domain.create();

function readSomeFile (filename, callback) {
    fs.readFile(filename, 'utf8', d.bind(function (error, data) {
        return callback(error, data ? JSON.parse(data) : null);
    }));
}
d.on('error', function (error) {});

//---------------------------------------------

var d = domain.create();

function readSomeFile(filename, callback) {
    fs.readFile(filename, 'utf8', d.intercept( function(data) {
        return callback(null, JSON.parse(data));
    }));
}
d.on('error', function (error) {});

//---------------------------------------------

var domain = require('domain');
var cluster = require('cluster');
var http = require('http');

var PORT = Number(process.env.PORT) || 1337;

if (cluster.isMaster) {
    cluster.fork();
    cluster.fork();
    cluster.on('disconnect', function (worker) {
        console.error('disconnect!');
        cluster.fork();
    });
} else {
    var server = http.createServer(function (request, response) {
        var d = domain.create();
        d.on('error', function (error) {
            console.error('error', error.stack);
            try {
                var killtimer = setTimeout(function () {process.exit(1);}, 30000);
                killtimer.unref();
                server.close();
                cluster.worker.disconnect();
                response.statusCode = 500;
                response.setHeader('content-type', 'text/plain');
                response.end('Oops, there was a problem!');
            } catch (error2) {
                console.error('Error sending 500!', error2.stack);
            }
        });
        d.add(request);
        d.add(response);
        d.run(function () {handleRequest(request, response);});
    });
    server.listen(PORT);
}

function handleRequest (request, response) {
    switch (request.url) {
        case '/error': setTimeout(function () {flerb.bark();});
                           break;
        default: response.end('ok');
    }
}

v8 - getHeapStatistics, getHeapSpaceStatistics, setFlagsFromString

var v8 = require('v8');

console.log(v8.getHeapStatistics());
// Return:
// {
// total_heap_size: 7326976,
// total_heap_size_executable: 4194304,
// total_physical_size: 7326976,
// total_available_size: 1152656,
// used_heap_size: 3476208,
// heap_size_limit: 1535115264,
// malloced_memory: 16384,
// peak_malloced_memory: 1127496,
// does_zap_garbage: 0
// }

console.log(v8.getHeapSpaceStatistics());
// Return:
// [
// {
// "space_name": "new_space",
// "space_size": 2063872,
// "space_used_size": 951112,
// "space_available_size": 80824,
// "physical_space_size": 2063872
// }, ...
// ]

v8.setFlagsFromString('--trace_gc');

os - uptime, cpus, totalmem, homedir, networkInterfaces

var os = require('os');

var string = 'some text' + os.EOL;

console.log(os.arch()); // === console.log(process.arch);
console.log(os.constants);
console.log(os.cpus().length);

          if (os.endianness() === 'BE') {console.log('big endian');
} else if (os.endianness() === 'LE') {console.log('little endian');
}

console.log(os.totalmem());
console.log(os.freemem());

console.log(os.homedir());
console.log(os.tmpdir());

console.log(os.hostname());

console.log(os.loadavg());

console.log(os.networkInterfaces());

console.log(os.platform());
console.log(os.type());
console.log(os.release());

console.log(os.uptime());

console.log(os.userInfo('utf8'));

console.log(os.constants.signals);

process - nextTick, argv, cwd, stdin, stdout, stderr

process.nextTick(function () {console.log('nextTick callback');}, ...args);

process.stdout.write('data');
process.stderr.write('data');

process.stdin.setEncoding('utf8');
process.stdin.on('readable', function () {
    var chunk = process.stdin.read();
    if (chunk !== null) {
        process.stdout.write('data: ' + chunk);
    }
});

process.stdin.on('end', () => {
  process.stdout.write('end');
});

process.send('some message', sendHandle, options, function () {});
process.on('message', function (message, socket) {});

process.disconnect();
if (process.connected) {}
process.on('disconnect', function () {});

process.exitCode = 25;
process.exit(1);
process.on('beforeExit', function () {});
process.on('exit', function (code) {console.log('exit with code: ' + code);});

var unhandledRejections = new Map();
process.on('unhandledRejection', function (reason, promise) {unhandledRejections.set(promise, reason);});
process.on('rejectionHandled', function (promise) {unhandledRejections.delete(promise);});

process.on('uncaughtException', function (error) {fs.writeSync(1, 'Caught exception: ' + error);});

process.emitWarning('Something Happened!', 'CustomWarning');
process.on('warning', function (warning) {
    console.warn(warning.name);    // Print the warning name
    console.warn(warning.message); // Print the warning message
    console.warn(warning.stack);   // Print the stack trace
});

process.stdin.resume();
process.on('SIGINT', function () {console.log('Received SIGINT.  Press Control-D to exit.');});

process.abort();
process.kill(process.pid, 'SIGHUP');

console.log(process.mainModule); // === require.main

console.log(process.execPath); // 'C:\\Node Training\\node.exe'
process.argv.forEach(function (arg, index) {console.log('' + index + ': ' + arg);}); // 'node' 'process-2.js' 'one two=three' 'four'
console.log(process.argv0); // 'node'
console.log(process.execArgv); // node ['--harmony'] script.js --version

console.log(process.cwd());
process.chdir('/tmp');

process.env.someVar = 1;

console.log('This process is pid ' + process.pid);

console.log(process.hrtime()); // [1800216, 25]
console.log(process.uptime());

console.log('This processor architecture is' + process.arch); // === os.arch();
console.log(process.cpuUsage(previousCpuUsageValue));
console.log(process.memoryUsage()); // {rss: 4935680, heapTotal: 1826816, heapUsed: 650472, external: 49879}

console.log('This platform is ' + process.platform);
console.log(process.release);
console.log(process.title);
console.log(process.version);
console.log(process.versions);

if (process.channel) {}

console.log(process.config);

process.umask(0o022);

if (process.getegid) {console.log('Current gid: ' + process.getegid());}
if (process.geteuid) {console.log('Current uid: ' + process.geteuid());}
if (process.getgid) {console.log('Current gid: ' + process.getgid());}
if (process.getuid) {console.log('Current uid: ' + process.getuid());}
console.log('Current groups: ' + process.getgroups());

process.initgroups('bnoordhuis', 1000); // switch user

process.setgroups(groups);
console.log(process.getgroups()); // [ 27, 30, 46, 1000, 0 ]

process.setgid(1000); // drop root gid
process.setuid(501);
process.seteuid(501);

child_process - execFile, exec, spawn, fork

var child_process = require('child_process');

//---------------------------------------------

child_process.execFile('node.exe', ['--version'], function (error, stdout, stderr) {
    if (error) {throw error;}
    console.log('stdout: ' + data);
    console.log('stderr: ' + data);
});

//---------------------------------------------

child_process.exec('ls -lh /usr', {shell: true}, function (error, stdout, stderr) {
    if (error) {throw error;}
    console.log('stdout: ' + data);
    console.log('stderr: ' + data);
});

//---------------------------------------------

var spawnProcess = child_process.spawn('ls', ['-lh', '/usr'], {shell: true});
spawnProcess.on('error', function (error) {throw error;});
spawnProcess.stdout.on('data', function (data) {console.log('stdout: ' + data);});
spawnProcess.stderr.on('data', function (data) {console.log('stderr: ' + data);});
spawnProcess.on('close', function (code, signal) {console.log('Child process exited with code ' + code);});
spawnProcess.on('exit', function (code, signal) {console.log('Child exited with code ' + code);});
spawnProcess.stdin.write('data');
spawnProcess.stdin.end();
spawnProcess.disconnect();
spawnProcess.kill('SIGHUP');
spawnProcess.unref();
console.log(spawnProcess.pid);

//---------------------------------------------

var childProcess = child_process.fork('gulp.js', ['build'], {cwd: undefined, env: process.env});

childProcess.on('message', function (message) {console.log('PARENT got message: ' + message.foo);});
childProcess.send({hello: 'world'});

process.on('message', function (message) {console.log('CHILD got message: ' + message.hello);});
process.send({foo: 'bar'});

childProcess.stderr.write('data');
childProcess.stdin.write('data');
childProcess.stdout.write('data');

childProcess.stdio[0] // child.stdin
childProcess.stdio[1] // child.stdout
childProcess.stdio[2] // child.stderr

cluster - isMaster, isWorker, fork

var cluster = require('cluster')
    , http = require('http')
    , os = require('os');

var numCPUs = os.cpus().length;

cluster.setupMaster({
    exec: 'worker.js',
    args: ['--use', 'https'],
    silent: true
});

if (cluster.isMaster) {
    console.log('Master ' + process.pid + ' is running');
    cluster.on('fork', function (worker) {
        console.log('Worker forked: ' + worker.id);
    });
    cluster.on('listening', function (worker, address) {
        console.log('Worker ' + worker.id + ' is now connected to ' + address.address + ':' + address.port);
    });
    cluster.on('online', function (worker) {
        console.log('Yay, the worker responded after it was forked');
    });
    cluster.on('exit', function (worker, code, signal) { // worker stop
        console.log('Worker ' + worker.process.pid + ' died');
        if (worker.exitedAfterDisconnect === true) {console.log('Oh, it was just voluntary – no need to worry');}
    });
    cluster.on('disconnect', function (worker) {
        console.log('The worker #' + worker.id + ' has disconnected');
    });
    cluster.on('message', function (worker, message, callback) {
        console.log('Worker ' + worker.id + ' got message: ' + message.cmd);
    });
    // Fork workers
    for (var i = 0; i < numCPUs; i++) {
        var worker = cluster.fork();
        worker.on('error', function (error) {throw error;});
        worker.on('listening', function (address) {
            console.log('Worker is listening: ' + worker.id);
            worker.send('shutdown');
            worker.disconnect();
            worker.kill('SIGTERM');
        });
        worker.on('online', function () {console.log('Worker is online: ' + worker.id);});
        worker.on('disconnect', function () {console.log('Worker has disconnected: ' + worker.id);});
        worker.on('exit', function (code, signal) {
                      if (signal) {console.log('Worker was killed by signal: ' + signal);
            } else if (code !== 0) {console.log('Worker exited with error code: ' + code);
            } else {console.log('Worker success!');
            }
        });

    }
    for (var id in cluster.workers) {
        cluster.workers[id].on('message', function (message) {console.log('Worker got message: ' + message.cmd);});
        if (cluster.workers[id].isConnected()) {}
        if (cluster.workers[id].isDead()) {}
    }
} else if (cluster.isWorker) {
    http.createServer(function (request, response) {
        response.writeHead(200, 'OK', {'Content-Type': 'text/html'});
        response.end('hello world');
    }).listen(80);
    console.log('Worker ' + process.pid + ' started'); // worker start
    console.log('I am worker ' + cluster.worker.id);
    process.on('error', function (error) {throw error;});
    process.on('message', function (message) {
        console.log('Master got message: ' + message.hello);
        if (message === 'shutdown') {console.log('Worker shutdown');}
    });
    process.send({cmd: 'notifyRequestToMaster'});
}

// node.exe server.js
// > Master 3596 is running
// > Worker 4324 started
// > Worker 4520 started
// > Worker 6056 started
// > Worker 5644 started

vm - eval script

var vm = require('vm');

//---------------------------------------------

var sandbox = {
    animal: 'cat',
    count: 2
};

var script = new vm.Script('count += 1; name = "kitty";');
var context = new vm.createContext(sandbox);
for (var i = 0; i < 10; ++i) {
    script.runInContext(context);
}

console.log(sandbox); // {animal: 'cat', count: 12, name: 'kitty'}

//---------------------------------------------

var sandboxes = [{}, {}, {}];

var script = new vm.Script('globalVar = "set"');
sandboxes.forEach(function (sandbox) {
    script.runInNewContext(sandbox);
});

console.log(sandboxes); // [{globalVar: 'set'}, {globalVar: 'set'}, {globalVar: 'set'}]

var sandbox = {
    animal: 'cat',
    count: 2
};

vm.runInNewContext('count += 1; name = "kitty"', sandbox);

console.log(sandbox); // {animal: 'cat', count: 3, name: 'kitty'}

//---------------------------------------------

global.globalVar = 0;

var script = new vm.Script('globalVar += 1', {filename: 'myfile.vm'});
for (var i = 0; i < 1000; ++i) {
    script.runInThisContext();
}

console.log(globalVar); // 1000

//---------------------------------------------

var globalVar = 3;

var sandbox = {globalVar: 1};

vm.createContext(sandbox);
vm.runInContext('globalVar *= 2;', sandbox);

console.log(sandbox); // 2
console.log(globalVar); // 3

//---------------------------------------------

var Debug = vm.runInDebugContext('Debug');
console.log(Debug.findScript(process.emit).name); // 'events.js'
console.log(Debug.findScript(process.exit).name); // 'internal/process.js'

//---------------------------------------------

var localVar = 'initial value';

var vmResult = vm.runInThisContext('localVar = "vm";');
console.log('vmResult:', vmResult); // vmResult: 'vm'
console.log('localVar:', localVar); // localVar: 'initial value'

var evalResult = eval('localVar = "eval";');
console.log('evalResult:', evalResult); // evalResult: 'eval'
console.log('localVar:', localVar); // localVar: 'eval'

//---------------------------------------------

if (vm.isContext(sandbox)) {}

//---------------------------------------------

// Running an HTTP Server within a VM

var vm = require('vm');

var code = `(function(require) {

    const http = require('http');

    http.createServer(function (request, response) {
        response.writeHead(200, {'Content-Type': 'text/plain'});
        response.end('Hello World');
    }).listen(8124);

    console.log('Server running at http://127.0.0.1:8124/');

})`;

vm.runInThisContext(code)(require);

repl - prompt

var repl = require('repl');

//---------------------------------------------

var message = 'message';
repl.start('> ').context.m = message;

//---------------------------------------------

var r = repl.start('> ');
Object.defineProperty(r.context, 'm', {
    configurable: false,
    enumerable: true,
    value: message
});

//---------------------------------------------

var Translator = require('translator').Translator;

var myTranslator = new Translator('en', 'fr');

function myEval(cmd, context, filename, callback) {
    callback(null, myTranslator.translate(cmd));
}

repl.start({prompt: '> ', eval: myEval});

//---------------------------------------------

var repl = require('repl');

var r = repl.start({prompt: '> ', eval: myEval, writer: myWriter});

function myEval (cmd, context, filename, callback) {
    callback(null, cmd);
}

function myWriter (output) {
    return output.toUpperCase();
}

//---------------------------------------------

var replServer = repl.start('> ');

function initializeContext(context) {context.m = 'test';}
initializeContext(replServer.context);
replServer.on('reset', initializeContext);

replServer.on('exit', function () {
    console.log('Received "exit" event from repl!');
    process.exit();
});

replServer.displayPrompt(true);

replServer.defineCommand('sayhello', {
    help: 'Say hello',
    action: function (name) {
        this.lineParser.reset();
        this.bufferedCommand = '';
        console.log('Hello, ' + name);
        this.displayPrompt();
    }
});
replServer.defineCommand('saybye', function () {
    console.log('Goodbye!');
    this.close();
});

> .sayhello Node.js User
Hello, Node.js User!

> .saybye
Goodbye!

//---------------------------------------------

// Starting multiple REPL instances against a single running instance

var net = require('net');
var repl = require('repl');

var connections = 0;

repl.start({
    prompt: 'Node.js via stdin> ',
    input: process.stdin,
    output: process.stdout
});

net.createServer(function (socket) {
    connections += 1;
    repl.start({
        prompt: 'Node.js via Unix socket> ',
        input: socket,
        output: socket
    }).on('exit', function () {
        socket.end();
    });
}).listen('/tmp/node-repl-sock');

net.createServer(function (socket) {
    connections += 1;
    repl.start({
        prompt: 'Node.js via TCP socket> ',
        input: socket,
        output: socket
    }).on('exit', function () {
        socket.end();
    });
}).listen(5001);

//---------------------------------------------

// Commands and Special Keys
// .break - When in the process of inputting a multi-line expression, entering the .break command (or pressing the <ctrl>-C key combination) will abort further input or processing of that expression.
// .clear - Resets the REPL context to an empty object and clears any multi-line expression currently being input.
// .exit - Close the I/O stream, causing the REPL to exit.
// .help - Show this list of special commands.
// .save - Save the current REPL session to a file: > .save ./file/to/save.js
// .load - Load a file into the current REPL session. > .load ./file/to/load.js
// .editor - Enter editor mode (<ctrl>-D to finish, <ctrl>-C to cancel)

// > .editor
// Entering editor mode (^D to finish, ^C to cancel)
// function welcome(name) {
//     return 'Hello ' + name + '!';
// }

readline - prompt and question

var readline = require('readline');

var rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});

rl.question('What do you think of Node.js? ', function (answer) {
    console.log('Thank you for your valuable feedback: ' + answer);
    rl.close();
});

rl.on('line', function (input) {console.log(Received: ' + input);});

rl.on('close', function () {});

rl.on('pause', function () {console.log('Readline paused.');});
rl.on('resume', function () {console.log('Readline resumed.');});

rl.on('SIGCONT', function () {
    rl.prompt(); // "prompt" will automatically resume the stream
});
rl.on('SIGINT', function () {
    rl.question('Are you sure you want to exit?', function (answer) {
        if (answer.match(/^y(es)?$/i)) {
            rl.pause();
        }
    });
});
rl.on('SIGTSTP', function () {
    // This will override SIGTSTP and prevent the program from going to the background.
    console.log('Caught SIGTSTP.');
});

rl.setPrompt(prompt);

rl.prompt(true);

rl.question('Are you sure you want to exit?', function (answer) {console.log(answer);});

rl.write('Delete this!');
rl.write('some text', {ctrl: true, name: 'u'}); // Simulate Ctrl+u to delete the line written previously
rl.write(null, {ctrl: true, name: 'u'});

rl.pause();
rl.resume();

rl.close();

readline.clearLine(process.stdout, 0);
readline.clearScreenDown(process.stdout);

readline.cursorTo(process.stdin, 5, 10);
readline.moveCursor(process.stdin, 5, 10);

readline.emitKeypressEvents(process.stdin, interface);

//---------------------------------------------

// Tiny CLI

var readline = require('readline');

var rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout,
    prompt: 'OHAI> '
});

rl.prompt();

rl.on('line', function (line) {
    switch(line.trim()) {
        case 'hello': console.log('world!');
                          break;
        default: console.log('Say what? I might have heard ' + line.trim());
    }
    rl.prompt();
}).on('close', function () {
    console.log('Have a great day!');
    process.exit(0);
});

//---------------------------------------------

// Read File Stream Line-by-Line

var readline = require('readline');
var fs = require('fs');

var rl = readline.createInterface({
    input: fs.createReadStream('sample.txt')
});

rl.on('line', (); (line) {
    console.log('Line from file: ' + line);
});

tty - text terminal resize, columns, rows

// Node.js detects that it is being run inside a text terminal ("TTY") context.

//---------------------------------------------

var tty = require('tty');

var readStream = tty.ReadStream();

if (readStream.isRaw) {}
readStream.setRawMode(mode);

//---------------------------------------------

var tty = require('tty');

var writeStream = tty.WriteStream();
writeStream.on('resize', function () {
    console.log('screen size has changed!');
    console.log(writeStream.columns);
    console.log(writeStream.rows);
});

//---------------------------------------------

process.stdout.on(function 'resize', () {
  console.log('screen size has changed!');
  console.log('' + process.stdout.columns + ' x ' + process.stdout.rows);
});

//---------------------------------------------

if (tty.isatty(fd)) {}

events - addListener, prependListener, removeLitener, on, once, emit

var EventEmitter = require('events');
var util = require('util');

class MyEmitter extends EventEmitter {}

var myEmitter = new MyEmitter();

myEmitter.setMaxListeners(myEmitter.getMaxListeners() + 1);

myEmitter.addListener('my-event', function eventHandler (a, b) {
    console.log('my event occurred! a = ' + a + ', b = ' + b);
});

myEmitter.prependListener('foo', function () {console.log('b');});
myEmitter.prependOnceListener('foo', function () {console.log('b');});

myEmitter.removeListener('my-event', eventHandler);
myEmitter.removeAllListeners('my-event');

myEmitter.on('my-event', function (a, b) {
    console.log('my event occurred! a = ' + a + ', b = ' + b);
    console.log(this); // MyEmitter {
                              //     domain: null,
                              //     _events: { event: [Function] },
                              //     _eventsCount: 1,
                              //     _maxListeners: undefined
                              // }
});
myEmitter.once('my-event', function (a, b) {
    console.log('my-event occurred! a = ' + a + ', b = ' + b);
});
myEmitter.once('newListener', function (event, listener) { // Отслеживание добавления новых событий
    if (event === 'my-event') {console.log('my-event listener added');}
});
myEmitter.emit('my-event', 'a', 'b');

process.on('uncaughtException', function (error) {console.log('whoops! there was an error');}); // Catch Node.js error
myEmitter.emit('error', new Error('whoops!')); // Throws and crashes Node.js

console.log(myEmitter.listenerCount('event'));
console.log(myEmitter.eventNames());
console.log(myEmitter.getMaxListeners());
console.log(util.inspect(myEmitter.listeners('my-event')));

path - dirname, basename, parse, format, join, resolve

var path = require('path');

console.log(path.dirname('/path/to/directory/file.txt')); // /path/to/directory

console.log(path.basename('/path/to/directory/file.txt', '.txt')); // file
console.log(path.win32.basename('/path/to/directory/file.txt', '.txt'));
console.log(path.posix.basename('/path/to/directory/file.txt', '.txt'));

console.log(path.extname('/path/to/directory/file.txt')); // .txt

console.log(process.env.PATH); // 'C:\Windows\system32;C:\Windows;C:\Program Files\node\'
console.log(process.env.PATH.split(path.delimiter)); // ['C:\\Windows\\system32', 'C:\\Windows', 'C:\\Program Files\\node\\']

var result = 'foo/bar/baz'.split(path.sep); // ['foo', 'bar', 'baz']
var result = 'foo/bar/baz'.split(path.win32.sep); // ['foo', 'bar', 'baz']

var result = path.parse('/home/user/dir/file.txt');
// {
//    root : "/",
//    dir : "/home/user/dir",
//    base : "file.txt",
//    ext : ".txt",
//    name : "file"
// }

var result = path.format({
    root: '/',
    name: 'file',
    ext: '.txt'
}); // /file.txt

var result = path.normalize('/foo/bar//baz/asdf/quux/..'); // '/foo/bar/baz/asdf'

var result = path.join('/foo', 'bar', 'baz/asdf', 'quux', '..'); // '/foo/bar/baz/asdf'

var result = path.resolve('/foo/bar', './baz'); '/foo/bar/baz'

var result = path.relative('/data/orandea/test/aaa', '/data/orandea/impl/bbb'); '../../impl/bbb'

if (path.isAbsolute('/foo/bar')) {}

fs - mkdir, readdir, rmdir, stat, open, read, write, close, writeFile, appendFile, rename, unlink

var fs = require('fs');

fs.mkdir('./../tmp', 0o777, function (error) {
    if (error) {throw error;}
    console.log('Directory created!');
});

fs.mkdtemp('/tmp/foo-', function (error, folder) {
    if (error) {throw error;}
    console.log('Temp directory created!');
    console.log(folder); // Prints: /tmp/foo-itXde2
});

fs.rmdir('./../tmp', function () {});

fs.readdir('./../tmp', options, function () {});

fs.open('./../tmp/hello.txt', 'wx', function (error, fd) {
    if (error) {
        if (error.code === "EEXIST") {
            console.error('myfile already exists');
            return;
        } else {
            throw error;
        }
    }
    readMyData(fd);
    writeMyData(fd);
});

fs.close(fd, function () {});

fs.read(fd, buffer, offset, length, position, function () {});

fs.readFile('./../tmp/hello.txt', 'utf8', function (error, data) {
    if (error) {throw error;}
    console.log(data);
});

fs.write(fd,'Hello Node.js', position, 'utf8', function (error) {
    if (error) {throw error;}
    console.log('It\'s saved!');
});

fs.writeFile('./../tmp/hello.txt', 'Hello Node.js', 'utf8', function (error) {
    if (error) {throw error;}
    console.log('It\'s saved!');
});

fs.appendFile('./../tmp/hello.txt', 'data to append', 'utf8', function (error) {
    if (error) {throw error;}
    console.log('The "data to append" was appended to file!');
});

var fd = fs.openSync('./../tmp/hello.txt', 'r+');
fs.ftruncate(fd, 10, function (err) {
    if (error) {throw error;}
    console.log(fs.readFileSync('./../tmp/hello.txt', 'utf8'));
});

fs.rename('./../tmp/hello.txt', './../tmp/world.txt', function (error) { // and move
    if (error) {throw error;}
    console.log('renamed complete');
});

fs.symlink(target, path, type, function () {});

fs.readlink('./../tmp/hello.txt', options, function () {});

fs.link('./../tmp/hello.txt', './some/other/dir/hello.txt', function (error) {
    if (error) {throw error;}
    console.log('successfully linked ./../tmp/hello.txt');
});

fs.unlink('./../tmp/hello.txt', function (error) {
    if (error) {throw error;}
    console.log('successfully deleted ./../tmp/hello.txt');
});

fs.stat('./../tmp/hello.txt', function (error, stats) {
    if (error) {throw error;}
    console.log('stats: ' + JSON.stringify(stats));
    console.log(stats.isFile());
    console.log(stats.isDirectory());
    console.log(stats.isBlockDevice());
    console.log(stats.isCharacterDevice());
    console.log(stats.isSymbolicLink()); // only valid with fs.lstat()
    console.log(stats.isFIFO());
    console.log(stats.isSocket());
});

fs.exists('./../tmp/hello.txt', function (exists) {
    console.log(exists ? 'it is there' : 'no hello.txt!');
});

fs.access('./../tmp/hello.txt', fs.constants.R_OK | fs.constants.W_OK, function (error) {
    console.log(error ? 'no access!' : 'can read/write');
});

fs.realpath('./../tmp/hello.txt', 'utf8', function () {});

fs.chmod('./../tmp/hello.txt', 0o777, function (error) {});
fs.chown('./../tmp/hello.txt', uid, gid, function (error) {});

fs.utimes('./../tmp/hello.txt', atime, mtime, function () {});

var fileWatcher = fs.watch('./../tmp/hello.txt', {encoding: 'buffer'}, function (eventType, filename) {
    if (filename) {
        console.log(filename); // Prints: <Buffer ...>
    }
});
fileWatcher.on('change', function (eventType, filename) { // eventType is either 'rename' or 'change'
    console.log('event type is: ' + eventType);
    if (filename) {
        console.log('filename provided: ' + filename); // Prints: <Buffer ...>
    } else {
        console.log('filename not provided');
    }
});
fileWatcher.on('error', function (error) {console.log(error);});
fileWatcher.close();

fs.watchFile('./../tmp/hello.txt', function (curr, prev) {
    console.log('current mtime is: ' + curr.mtime);
    console.log('previous mtime was: ' + prev.mtime);
});

fs.unwatchFile('./../tmp/hello.txt', listenerFunction);

var readStream = fs.createReadStream('./../tmp/hello.txt', {start: 90, end: 99});
var writeStream = fs.createWriteStream('./../tmp/hello.txt', {flags: 'w', defaultEncoding: 'utf8', fd: null, mode: 0o666, autoClose: true});

//---------------------------------------------

var fs = require('fs');

var writeStream = fs.createWriteStream('example.txt');

writeStream.write('some data');
writeStream.write('some more data');
writeStream.end('done writing data');

writeStream.on('drain', function () {writeStream.write('text', 'utf8', function () {})});
writeStream.once('drain', function () {writeStream.write('text', 'utf8', function () {})});

readStream.pipe(writeStream);
writeStream.on('pipe', function (source) {console.log('something is piping into the writer');});

readStream.pipe(writeStream);
readStream.unpipe(writeStream);
writeStream.on('unpipe', function (source) {console.error('Something has stopped piping into the writer.');});

writeStream.on('error', function (error) {console.log(error);});

writeStream.end('This is the end');
writeStream.on('finish', function () {console.error('All writes are now ended.');});

writeStream.on('close', function () {});

writeStream.cork();
writeStream.write('some');
writeStream.write('data');
process.nextTick(function () {
    writeStream.uncork();
});

writeStream.cork();
writeStream.write('some');
writeStream.cork();
writeStream.write('data');
process.nextTick(function () {
    writeStream.uncork();
    writeStream.uncork(); // The data will not be flushed until uncork() is called a second time.
});

writeStream.setDefaultEncoding('utf8')
writeStream.write('data', 'utf8', function () {});
writeStream.end('data', 'utf8', function () {});

function write (data, callback) {
    if (!writeStream.write(data)) {
        writeStream.once('drain', callback)
    } else {
        process.nextTick(callback)
    }
}
// Wait for callback to be called before doing any other write.
write('hello', function () {console.log('write completed, do more writes now')})

//---------------------------------------------

var fs = require('fs');

var readStream = fs.createReadStream('example.txt');

readStream.on('readable', function () {
    var chunk = readStream.read();
    while (null !== chunk) {
        console.log('Received ' + chunk.length + ' bytes of data.');
        chunk = readStream.read();
    }
});

readStream.on('data', function (data) {writeStream.write(data.length);});
readStream.on('end', function (data) {writeStream.end(data.length);});

readStream.on('error', function (error) {console.log(error);});

readStream.on('close', function () {});

if (readStream.isPaused()) {
    readStream.resume();
} else {
    readStream.pause();
}

readStream.setEncoding('utf8');

readStream.on('data',  function (data) {
    console.log('Received ' + data.length +' bytes of data.');
    readable.pause();
    console.log('There will be no additional data for 1 second.');
    setTimeout(function () {
        console.log('Now data will start flowing again.');
        readable.resume();
    }, 1000);
});

readStream.pipe(writeStream);
readStream.unpipe(writeStream);
writeStream.end();

var readStream = fs.createReadStream('file.txt');
var zipStream = zlib.createGzip();
var writeStream = fs.createWriteStream('file.txt.gz');
readStream.pipe(zipStream).pipe(writeStream);

readStream.pipe(writeStream, {end: false});
readStream.on('end', function () {
    writeStream.end('Goodbye');
});

readStream.read(size);
readable.on('readable', function () {
    var chunk = readStream.read();
    while (null !== chunk) {
        console.log('Received ' + chunk.length + ' bytes of data.');
        chunk = readStream.read();
    }
});

readStream.wrap(stream);

var OldReader = require('./old-api-module.js').OldReader;
var Readable = require('stream').Readable;

var oreader = new OldReader;
var myReader = new Readable().wrap(oreader);

myReader.on('readable', function () {
    myReader.read(); // etc.
});

readStream.unshift(chunk);

zlib - createGzip, createGunzip, createDeflate, unzip

// Compressing or decompressing a stream (such as a file)

var zlib = require('zlib');

var gzip = zlib.createGzip();
var fs = require('fs');

var inp = fs.createReadStream('input.txt');
var out = fs.createWriteStream('input.txt.gz');

inp.pipe(gzip).pipe(out);

//---------------------------------------------

// Compress or decompress data in a single step:

var zlib = require('zlib');

var input = '.................................';
zlib.deflate(input, function (error, buffer) {
    if (!error) {
        console.log(buffer.toString('base64'));
    } else {
        // handle error
    }
});

var buffer = Buffer.from('eJzT0yMAAGTvBe8=', 'base64');
zlib.unzip(buffer, function (error, buffer) {
    if (!error) {
    console.log(buffer.toString());
    } else {
    // handle error
  }
});

//---------------------------------------------

// Compressing HTTP requests and responses

// Client request example

var zlib = require('zlib');
var http = require('http');
var fs = require('fs');

var request = http.get({
    host: 'example.com',
    path: '/',
    port: 80,
    headers: {'Accept-Encoding': 'gzip,deflate'}
});

request.on('response', function (response) {
    var output = fs.createWriteStream('example.com_index.html');
    switch (response.headers['content-encoding']) {
        // or, just use zlib.createUnzip() to handle both cases
        case 'gzip': response.pipe(zlib.createGunzip()).pipe(output); break;
        case 'deflate': response.pipe(zlib.createInflate()).pipe(output); break;
        default: response.pipe(output);
    }
});

// Server example

// Running a gzip operation on every request is quite expensive.
// It would be much more efficient to cache the compressed buffer.

var zlib = require('zlib');
var http = require('http');
var fs = require('fs');

http.createServer(function (request, response) {
    var raw = fs.createReadStream('index.html');
    var acceptEncoding = request.headers['accept-encoding'];
    if (!acceptEncoding) {acceptEncoding = '';}
    // Note: this is not a conformant accept-encoding parser.
    // See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.3
    if (acceptEncoding.match(/\bdeflate\b/)) {
        response.writeHead(200, {'Content-Encoding': 'deflate'});
        raw.pipe(zlib.createDeflate()).pipe(response);
    } else if (acceptEncoding.match(/\bgzip\b/)) {
        response.writeHead(200, {'Content-Encoding': 'gzip'});
        raw.pipe(zlib.createGzip()).pipe(response);
    } else {
        response.writeHead(200, {});
        raw.pipe(response);
    }
}).listen(1337);


// This is a truncated version of the buffer from the above examples

var buffer = Buffer.from('eJzT0yMA', 'base64');

zlib.unzip(buffer, {finishFlush: zlib.constants.Z_SYNC_FLUSH}, function (error, buffer) {
    if (!error) {
        console.log(buffer.toString());
    } else {
        // handle error
    }
});

//---------------------------------------------

// Flushing

var zlib = require('zlib');
var http = require('http');

http.createServer(function (request, response) {
    // For the sake of simplicity, the Accept-Encoding checks are omitted.
    response.writeHead(200, {'content-encoding': 'gzip'});
    var output = zlib.createGzip();
    output.pipe(response);
    setInterval(function () {
        output.write('The current time is ' + Date() + '\n', function () {
            // The data has been passed to zlib, but the compression algorithm may
            // have decided to buffer the data for more efficient compression.
            // Calling .flush() will make the data available as soon as the client
            // is ready to receive it.
            output.flush();
        });
    }, 1000);
}).listen(1337);

crypto - createCipher, createDecipher, createDiffieHellman, computeSecret, createHash

var crypto = require('crypto');

//---------------------------------------------

// Detecting crypto support available
var crypto;
try {
    crypto = require('crypto');
} catch (error) {
    console.log('crypto support is disabled!');
}

//---------------------------------------------

var cert = new crypto.Certificate();

//---------------------------------------------

var crypto = require('crypto');
var fs = require('fs');

var cipher = crypto.createCipher('aes192', 'password');

//-----------------

var input = fs.createReadStream('test.js');
var output = fs.createWriteStream('test.enc');
input.pipe(cipher).pipe(output);

//-----------------

var encrypted = cipher.update('some clear text data', 'utf8', 'hex');
encrypted += cipher.final('hex');
console.log(encrypted);

//-----------------

var encrypted = '';
cipher.on('readable', function () {
    var data = cipher.read();
    if (data) {encrypted += data.toString('hex');}
});
cipher.on('end', function () {
    console.log(encrypted); // ca981be48e90867604588e75d04feabb63cc007a8f8ad89b10616ed84d815504
});
cipher.write('some clear text data');
cipher.end();

//---------------------------------------------

var crypto = require('crypto');
var fs = require('fs');

var decipher = crypto.createDecipher('aes192', 'password');

//-----------------

var input = fs.createReadStream('test.enc');
var output = fs.createWriteStream('test.js');
input.pipe(decipher).pipe(output);

//-----------------

var encrypted = 'ca981be48e90867604588e75d04feabb63cc007a8f8ad89b10616ed84d815504';
var decrypted = decipher.update(encrypted, 'hex', 'utf8');
decrypted += decipher.final('utf8');
console.log(decrypted);

//-----------------

var decrypted = '';
decipher.on('readable', function () {
    var data = decipher.read();
    if (data) {decrypted += data.toString('utf8');}
});
decipher.on('end', function () {
    console.log(decrypted); // some clear text data
});
var encrypted = 'ca981be48e90867604588e75d04feabb63cc007a8f8ad89b10616ed84d815504';
decipher.write(encrypted, 'hex');
decipher.end();

//---------------------------------------------

var crypto = require('crypto');
var assert = require('assert');

// Generate Alice's keys
var alice = crypto.createDiffieHellman(2048);
var aliceKey = alice.generateKeys();

// Generate Bob's keys
var bob = crypto.createDiffieHellman(alice.getPrime(), alice.getGenerator());
var bobKey = bob.generateKeys();

// Exchange and generate the secret
var aliceSecret = alice.computeSecret(bobKey);
var bobSecret = bob.computeSecret(aliceKey);

// OK
assert.strictEqual(aliceSecret.toString('hex'), bobSecret.toString('hex'));

//---------------------------------------------

var crypto = require('crypto');

var alice = crypto.getDiffieHellman('modp14');
var bob = crypto.getDiffieHellman('modp14');

alice.generateKeys();
bob.generateKeys();

var aliceSecret = alice.computeSecret(bob.getPublicKey(), null, 'hex');
var bobSecret = bob.computeSecret(alice.getPublicKey(), null, 'hex');

// aliceSecret and bobSecret should be the same
console.log(aliceSecret === bobSecret);

//---------------------------------------------

var crypto = require('crypto');
var assert = require('assert');

// Generate Alice's keys
var alice = crypto.createECDH('secp521r1');
var aliceKey = alice.generateKeys();

// Generate Bob's keys
var bob = crypto.createECDH('secp521r1');
var bobKey = bob.generateKeys();

// Exchange and generate the secret
var aliceSecret = alice.computeSecret(bobKey);
var bobSecret = bob.computeSecret(aliceKey);

// OK
assert.strictEqual(aliceSecret.toString('hex'), bobSecret.toString('hex'));

//---------------------------------------------

var crypto = require('crypto');
var fs = require('fs');

var hash = crypto.createHash('sha256');

//-----------------

var input = fs.createReadStream('test.js');
input.pipe(hash).pipe(process.stdout);

//-----------------

hash.update('some data to hash');
console.log(hash.digest('hex')); // 6a2da20943931e9834fc12cfe5bb47bbd9ae43489a30726962b576f4e3993e50

//-----------------

var hash = crypto.createHash('sha256');
hash.on('readable', function () {
    var data = hash.read();
    if (data) {console.log(data.toString('hex'));} // 6a2da20943931e9834fc12cfe5bb47bbd9ae43489a30726962b576f4e3993e50
});
hash.write('some data to hash');
hash.end();

//---------------------------------------------

var crypto = require('crypto');
var fs = require('fs');

var hmac = crypto.createHmac('sha256', 'secret');

//-----------------

var input = fs.createReadStream('test.js');
input.pipe(hmac).pipe(process.stdout);

//-----------------

hmac.update('some data to hash');
console.log(hmac.digest('hex')); // 7fd04df92f636fd450bc841c9418e5825c17f33ad9c87c518115a45971f7f77e

//-----------------

hmac.on('readable', function () {
    var data = hmac.read();
    if (data) {console.log(data.toString('hex'));} // 7fd04df92f636fd450bc841c9418e5825c17f33ad9c87c518115a45971f7f77e
});
hmac.write('some data to hash');
hmac.end();

//-----------------

var secret = 'abcdefg';
var hash = crypto.createHmac('sha256', secret)
                           .update('I love cupcakes')
                           .digest('hex');
console.log(hash);

//---------------------------------------------

var crypto = require('crypto');

var sign = crypto.createSign('RSA-SHA256');

//-----------------

sign.update('some data to sign');

//-----------------

sign.write('some data to sign');
sign.end();

var privateKey = getPrivateKeySomehow();
console.log(sign.sign(privateKey, 'hex'));

//-----------------

var sign = crypto.createSign('sha256');

sign.update('some data to sign');

var privateKey ='-----BEGIN EC PRIVATE KEY-----'
                     + 'MHcCAQEEIF+jnWY1D5kbVYDNvxxo/Y+ku2uJPDwS0r/VuPZQrjjVoAoGCCqGSM49'
                     + 'AwEHoUQDQgAEurOxfSxmqIRYzJVagdZfMMSjRNNhB8i3mXyIMq704m2m52FdfKZ2'
                     + 'pQhByd5eyj3lgZ7m7jbchtdgyOF8Io/1ng=='
                     + '-----END EC PRIVATE KEY-----';

console.log(sign.sign(privateKey).toString('hex'));

//---------------------------------------------

var crypto = require('crypto');

var verify = crypto.createVerify('RSA-SHA256');

//-----------------

verify.update('some data to sign');

//-----------------

verify.write('some data to sign');
verify.end();

var publicKey = getPublicKeySomehow();
var signature = getSignatureToVerify();
console.log(verify.verify(publicKey, signature)); // Prints: true or false

//---------------------------------------------

var crypto = require('crypto');
var fs = require('fs');

var filename = process.argv[2];

var hash = crypto.createHash('sha256');

var input = fs.createReadStream(filename);
input.on('readable', function () {
    var data = input.read();
    if (data) {
        hash.update(data);
    } else {
        console.log('' + hash.digest('hex') + ' ' + filename);
    }
});

//---------------------------------------------

var crypto = require('crypto');
var fs = require('fs');

var filename = process.argv[2];

var hmac = crypto.createHmac('sha256', 'secret');

var input = fs.createReadStream(filename);
input.on('readable', function () {
    var data = input.read();
    if (data) {
        hmac.update(data);
    } else {
        console.log('' + hmac.digest('hex') + ' ' + filename);
    }
});

//---------------------------------------------

var ciphers = crypto.getCiphers();
console.log(ciphers); // ['aes-128-cbc', 'aes-128-ccm', ...]

//---------------------------------------------

var curves = crypto.getCurves();
console.log(curves); // ['Oakley-EC2N-3', 'Oakley-EC2N-4', ...]

//---------------------------------------------

var hashes = crypto.getHashes();
console.log(hashes); // ['DSA', 'DSA-SHA', 'DSA-SHA1', ...]

//---------------------------------------------

var crypto = require('crypto');

crypto.pbkdf2('secret', 'salt', 100000, 512, 'sha512', function (error, key) {
    if (error) {throw error;}
    console.log(key.toString('hex'));  // '3745e48...aa39b34'
});

//---------------------------------------------

var crypto = require('crypto');

crypto.randomBytes(256, function (error, buf) {
    if (error) {throw error;}
    console.log('' + buf.length + ' bytes of random data: ' + buf.toString('hex'));
});

punycode - encode, decode, toASCII, toUnicode

var punycode = require('punycode');

console.log(punycode.version); // 2.0.0

console.log(punycode.decode('maana-pta')); // 'mañana'
console.log(punycode.encode('mañana')); // 'maana-pta'

console.log(punycode.toASCII('mañana.com'));  // 'xn--maana-pta.com'
console.log(punycode.toUnicode('xn--maana-pta.com')); // 'mañana.com'

console.log(punycode.ucs2.decode('abc')); // [0x61, 0x62, 0x63]
console.log(punycode.ucs2.encode([0x61, 0x62, 0x63])); // 'abc'

stream - Readable, Writable, Duplex, Transform, createReadStream, createWriteStream

var Writable = require('stream').Writable;

class MyWritable extends Writable {
    constructor(options) {
        super(options);
    }
    _write (chunk, encoding, callback) {
        if (chunk.toString().indexOf('a') >= 0) {
            callback(new Error('chunk is invalid'));
        } else {
            callback();
        }
    }
}

var myWritable = new MyWritable({
    write: function (chunk, encoding, callback) {
        if (chunk.toString().indexOf('a') >= 0) {
            callback(new Error('chunk is invalid'));
        } else {
            callback();
        }
    },
    writev: function (chunks, callback) {
        // ...
    }
});

//---------------------------------------------

const Readable = require('stream').Readable;

class MyReadable extends Readable {
    constructor(options) {
        super(options);
        this._source = getLowlevelSourceObject();
        this._source.ondata = function (chunk) {
            if (!this.push(chunk)) {
                this._source.readStop();
            }
        };
        this._source.onend = function () {
            this.push(null);
        };
    }
    _read (size) {
        this._source.readStart();
    }
}

var myReadable = new MyReadable({
    read: function (size) {
        if (checkSomeErrorCondition()) {
            process.nextTick(function () {this.emit('error', error);});
            return;
        }
        // do some work
    }
});

//---------------------------------------------

// Example of Counting Stream

const Readable = require('stream').Readable;

class Counter extends Readable {
    constructor(opt) {
        super(opt);
        this._max = 1000000;
        this._index = 1;
    }
    _read() {
        var i = this._index++;
        if (i > this._max) {
            this.push(null);
        } else {
            var str = '' + i;
            var buf = Buffer.from(str, 'ascii');
            this.push(buf);
        }
    }
}

//---------------------------------------------

var Duplex = require('stream').Duplex;

var kSource = Symbol('source');

class MyDuplex extends Duplex {
    constructor(source, options) {
        super(options);
        this[kSource] = source;
    }
    _write(chunk, encoding, callback) {
        if (Buffer.isBuffer(chunk)) {
            chunk = chunk.toString();
        }
        this[kSource].writeSomeData(chunk);
        callback();
    }
    _read(size) {
        this[kSource].fetchSomeData(size, function (data, encoding) {
            this.push(Buffer.from(data, encoding));
        });
    }
}

var myDuplex = new MyDuplex({
    read: function (size) {
        // ...
    },
    write function (chunk, encoding, callback) {
        // ...
    }
});

//---------------------------------------------

var Transform = require('stream').Transform;

class MyTransform extends Transform {
    constructor(options) {
        super(options);
    }
    _transform (data, encoding, callback) {
        this.push(data);
        callback();
    }
}

var myTransform = new Transform({
    transform: function (chunk, encoding, callback) {
        // ...
    }
});

//---------------------------------------------

var Transform = require('stream').Transform;

// All Transform streams are also Duplex Streams
var myTransform = new Transform({
    writableObjectMode: true,
    transform: function (chunk, encoding, callback) {
        chunk |= 0; // Coerce the chunk to a number if necessary
        var data = chunk.toString(16); // Transform the chunk into something else.
        callback(null, '0'.repeat(data.length % 2) + data); // Push the data onto the readable queue.
    }
});

myTransform.setEncoding('ascii');
myTransform.on('data', function (chunk) {console.log(chunk);});

myTransform.write(1); // Prints: 01
myTransform.write(10); // Prints: 0a
myTransform.write(100); // Prints: 64

//---------------------------------------------

var fs = require('fs');

var writeStream = fs.createWriteStream('example.txt');

writeStream.write('some data');
writeStream.write('some more data');
writeStream.end('done writing data');

writeStream.on('drain', function () {writeStream.write('text', 'utf8', function () {})});
writeStream.once('drain', function () {writeStream.write('text', 'utf8', function () {})});

readStream.pipe(writeStream);
writeStream.on('pipe', function (source) {console.log('something is piping into the writer');});

readStream.pipe(writeStream);
readStream.unpipe(writeStream);
writeStream.on('unpipe', function (source) {console.error('Something has stopped piping into the writer.');});

writeStream.on('error', function (error) {console.log(error);});

writeStream.end('This is the end');
writeStream.on('finish', function () {console.error('All writes are now ended.');});

writeStream.on('close', function () {});

writeStream.cork();
writeStream.write('some');
writeStream.write('data');
process.nextTick(function () {
    writeStream.uncork();
});

writeStream.cork();
writeStream.write('some');
writeStream.cork();
writeStream.write('data');
process.nextTick(function () {
    writeStream.uncork();
    writeStream.uncork(); // The data will not be flushed until uncork() is called a second time.
});

writeStream.setDefaultEncoding('utf8')
writeStream.write('data', 'utf8', function () {});
writeStream.end('data', 'utf8', function () {});

function write (data, callback) {
    if (!writeStream.write(data)) {
        writeStream.once('drain', callback)
    } else {
        process.nextTick(callback)
    }
}
// Wait for callback to be called before doing any other write.
write('hello', function () {console.log('write completed, do more writes now')})

//---------------------------------------------

var stream = require('stream');
var fs = require('fs');

var readStream = fs.createReadStream('example.txt');

readStream.on('readable', function () {
    var chunk = readStream.read();
    while (null !== chunk) {
        console.log('Received ' + chunk.length + ' bytes of data.');
        chunk = readStream.read();
    }
});

readStream.on('data', function (data) {writeStream.write(data.length);});
readStream.on('end', function (data) {writeStream.end(data.length);});

readStream.on('error', function (error) {console.log(error);});

readStream.on('close', function () {});

if (readStream.isPaused()) {
    readStream.resume();
} else {
    readStream.pause();
}

readStream.setEncoding('utf8');

readStream.on('data',  function (data) {
    console.log('Received ' + data.length +' bytes of data.');
    readable.pause();
    console.log('There will be no additional data for 1 second.');
    setTimeout(function () {
        console.log('Now data will start flowing again.');
        readable.resume();
    }, 1000);
});

readStream.pipe(writeStream);
readStream.unpipe(writeStream);
writeStream.end();

var readStream = fs.createReadStream('file.txt');
var zipStream = zlib.createGzip();
var writeStream = fs.createWriteStream('file.txt.gz');
readStream.pipe(zipStream).pipe(writeStream);

readStream.pipe(writeStream, {end: false});
readStream.on('end', function () {
    writeStream.end('Goodbye');
});

readStream.read(size);
readable.on('readable', function () {
    var chunk = readStream.read();
    while (null !== chunk) {
        console.log('Received ' + chunk.length + ' bytes of data.');
        chunk = readStream.read();
    }
});

readStream.wrap(stream);

var OldReader = require('./old-api-module.js').OldReader;
var Readable = require('stream').Readable;

var oreader = new OldReader;
var myReader = new Readable().wrap(oreader);

myReader.on('readable', function () {
    myReader.read(); // etc.
});

readStream.unshift(chunk);

//---------------------------------------------

// Unshift example
// Pull off a header delimited by \n\n
// use unshift() if we get too much
// Call the callback with (error, header, stream)
var StringDecoder = require('string_decoder').StringDecoder;
function parseHeader(stream, callback) {
    stream.on('error', callback);
    stream.on('readable', onReadable);
    var decoder = new StringDecoder('utf8');
    var header = '';
    function onReadable () {
        var chunk;
        while (null !== (chunk = stream.read())) {
            var str = decoder.write(chunk);
            if (str.match(/\n\n/)) {
                // found the header boundary
                var split = str.split(/\n\n/);
                header += split.shift();
                var remaining = split.join('\n\n');
                var buf = Buffer.from(remaining, 'utf8');
                stream.removeListener('error', callback);
                // set the readable listener before unshifting
                stream.removeListener('readable', onReadable);
                if (buf.length) {stream.unshift(buf);}
                // now the body of the message can be read from the stream.
                callback(null, header, stream);
            } else {
                // still reading the header.
                header += str;
            }
        }
    }
}

buffer - alloc, from, concat, length, byteLength, keys, values, entries

var buf = Buffer.alloc(10, 'a');
buf.fill('b', 0, 5, 'utf8');
buf.write('string', 0);

//---------------------------------------------

var buf = Buffer.from([1, 2, 3]);
var buf = Buffer.from('test', 'utf8');

//---------------------------------------------

buf.toString('utf8', 0, 5);
buf.toJSON();
JSON.stringify(buf);

//---------------------------------------------

console.log(buf.length);
console.log(Buffer.byteLength('string', 'utf8');

//---------------------------------------------

var bufArray = [buf1, buf2];
console.log(bufArray.sort(Buffer.compare));

//---------------------------------------------

var buf2 = buf1.slice(0, 5);
var buf = Buffer.concat([buf1, buf2, buf3], buf1.length + buf2.length + buf3.length);
buf1.copy(buf2, 8, 16, 20);

//---------------------------------------------

if (buf1.equals(buf2)) {}
if (buf.includes('word', 5, 'utf8')) {}
if (Buffer.isBuffer(buf)) {}
if (Buffer.isEncoding('utf8')) {}
var buf = buffer.transcode(Buffer.from('€'), 'utf8', 'ascii');

//---------------------------------------------

buf[i] = str.charCodeAt(i);

//---------------------------------------------

console.log(buf.keys());
console.log(buf.values());
console.log(buf.entries());

//---------------------------------------------

console.log(buf.indexOf('word', 5, 'utf8'));
console.log(buf.lastIndexOf('word', 5, 'utf8'));

//---------------------------------------------

Buffer.poolSize = 1000;

string_decoder - write, end

var StringDecoder = require('string_decoder').StringDecoder;

var decoder = new StringDecoder('utf8');

var cent = Buffer.from([0xC2, 0xA2]);
console.log(decoder.write(cent));

var euro = Buffer.from([0xE2, 0x82, 0xAC]);
console.log(decoder.write(euro));

decoder.write(Buffer.from([0xE2]));
decoder.write(Buffer.from([0x82]));

console.log(decoder.end(Buffer.from([0xAC])));

url - parse, format, resolve

var url = require('url');

var urlString = 'http://user:pass@host.com:8080/p/a/t/h?query=string#hash';

var urlObject = url.parse(urlString, parseQueryString, slashesDenoteHost);
// parseQueryString = true --> urlObject.query = {'query': 'string'}
// slashesDenoteHost = true --> urlString = '//foo/bar'; --> {host: 'foo', pathname: '/bar', ...}

console.log(urlObject.href); // 'http://user:pass@host.com:8080/p/a/t/h?query=string#hash'
console.log(urlObject.protocol); // 'http:'
console.log(urlObject.slashes); // '//'
console.log(urlObject.auth); // 'user:pass'
console.log(urlObject.host); // 'host.com:8080'
console.log(urlObject.hostname); // 'host.com'
console.log(urlObject.port); // '8080'
console.log(urlObject.path); // '/p/a/t/h?query=string'
console.log(urlObject.pathname); // '/p/a/t/h'
console.log(urlObject.search); // '?query=string'
console.log(urlObject.query); // 'query=string' или {'query': 'string'}
console.log(urlObject.hash); // '#hash'

urlString = url.format(urlObject); // 'http://user:pass@host.com:8080/p/a/t/h?query=string#hash'

urlString = url.resolve('/one/two/three', 'four'); // '/one/two/four'
urlString = url.resolve('http://example.com/', '/one'); // 'http://example.com/one'
urlString = url.resolve('http://example.com/one', '/two'); // 'http://example.com/two'

Escaped Characters: < > " ` \r \n \t { } | \ ^ '
// (' ') is encoded as %20
// (/) is encoded as %3C

//---------------------------------------------

// The WHATWG URL API

var URL = require('url').URL;

var myURL = new URL({toString: function () {return 'https://example.org/';}); // https://example.org/
var myURL = new URL('https://你好你好'); // https://xn--6qqa088eba

var myURL = new URL('/foo', 'https://example.org/'); // https://example.org/foo
var myURL = new URL('https://example.org/foo'); // https://example.org/foo

var myURL = new URL('http://user:pass@host.com:8080/p/a/t/h?query=string#hash');
console.log(myURL.href); // 'http://user:pass@host.com:8080/p/a/t/h?query=string#hash'
console.log(myURL.origin); // 'https://host.com'
console.log(myURL.protocol); // 'https:'
console.log(myURL.username); // 'user'
console.log(myURL.password); // 'pass'
console.log(myURL.host); // 'host.com:8080'
console.log(myURL.hostname); // 'host.com'
console.log(myURL.port); // '8080'
console.log(myURL.pathname); // '/p/a/t/h'
console.log(myURL.search); // ?query=string
console.log(myURL.searchParams.query); // 'string'
console.log(myURL.hash); // '#hash'

var urlString = myURL.toString(); // 'http://user:pass@host.com:8080/p/a/t/h?query=string#hash'

//---------------------------------------------

// URLSearchParams

var URL = require('url').URL;

var myURL = new URL('http://user:pass@host.com:8080/p/a/t/h?query=string#hash');

console.log(myURL.searchParams.get('query')); // 'string'

myURL.searchParams.append('abc', 'xyz');
console.log(myURL.href); // 'http://user:pass@host.com:8080/p/a/t/h?query=string&abc=xyz#hash'

myURL.searchParams.delete('abc');
console.log(myURL.href); // 'http://user:pass@host.com:8080/p/a/t/h?query=string#hash'

myURL.searchParams.set('query', 'xyz');
console.log(myURL.href); // 'http://user:pass@host.com:8080/p/a/t/h?query=xyz#hash'

console.log(myURL.urlSearchParams.keys());
console.log(myURL.urlSearchParams.values());
console.log(myURL.urlSearchParams.entries());

console.log(myURL.urlSearchParams.get('query'));
console.log(myURL.urlSearchParams.getAll('query'));

if (myURL.urlSearchParams.has('query')) {}

myURL.urlSearchParams.set('query', 'xyz'));

console.log(myURL.urlSearchParams.toString()); // 'query=string'

myURL.urlSearchParams.forEach(function (value, name) {
    console.log(name + '=' + value); // 'query=string'
})l

//---------------------------------------------

var urlString =require('url').domainToAscii('http://user:pass@host.com:8080/p/a/t/h?query=string&abc=xyz#hash');
var urlString = require('url').domainToUnicode('http://user:pass@host.com:8080/p/a/t/h?query=string&abc=xyz#hash');

//---------------------------------------------

var URL = require('url').URL;

var myURL = new URL('https://%CF%80.com/foo');

console.log(myURL.href); // 'https://xn--1xa.com/foo'

console.log(myURL.origin); // 'https://π.com'

querystring - parse, stringify, escape, unescape

var querystring = require('querystring');

querystring.parse('foo=bar&abc=xyz&abc=123', '&', '=', {decodeURIComponent: function () {}}); // {foo: 'bar', abc: ['xyz', '123']}

querystring.stringify({foo: 'bar', abc: ['xyz', '123']}, '&', '=', {encodeURIComponent: function () {}}); // 'foo=bar&abc=xyz&abc=123'

querystring.escape('А'); // %D0%90
querystring.unescape('%D0%90'); // 'А'

dns - lookup, lookupService, resolve4

var dns = require('dns');

dns.lookup('nodejs.org', function (err, addresses, family) {
    console.log('addresses:', addresses);
});

//---------------------------------------------

var dns = require('dns');

dns.lookupService('127.0.0.1', 22, function (error, hostname, service) {
    console.log(hostname, service); // Prints: localhost ssh
});

//---------------------------------------------

var dns = require('dns');

dns.resolve4('nodejs.org', function (error, addresses) {
    if (error) {throw error;}
    console.log(`addresses: ${JSON.stringify(addresses)}`);
    addresses.forEach(function (address) {
        dns.reverse(address, function (error, hostnames) {
            if (error) {throw error;}
            console.log('reverse for ' + address + ': ' + JSON.stringify(hostnames));
        });
    });
});

http, https - Agent, get, request, createServer

var http = require('http');

console.log(http.METHODS);
console.log(http.STATUS_CODES);

//---------------------------------------------

var keepAliveAgent = new http.Agent({keepAlive: true});

http.request({agent: keepAliveAgent}, function (response) {});

keepAliveAgent.createConnection(options, callback);
keepAliveAgent.destroy();

console.log(keepAliveAgent.freeSockets);
console.log(keepAliveAgent.getName(options));
console.log(keepAliveAgent.maxFreeSockets);
console.log(keepAliveAgent.maxSockets);
console.log(keepAliveAgent.requests);
console.log(keepAliveAgent.sockets);

//---------------------------------------------

http.get({
    hostname: '127.0.0.1',
    port: 80,
    path: '/',
    agent: false // create a new http.Agent just for this one request
}, function (response) {
    var statusCode = response.statusCode;
    var contentType = response.headers['content-type'];
    var error;
    if (statusCode !== 200) {
        error = new Error('Request Failed. Status Code: ' + statusCode);
    } else if (!/^application\/json/.test(contentType)) {
        error = new Error('Invalid content-type. Expected application/json but received ' + contentType);
    }
    if (error) {
        console.log(error.message);
        response.resume(); // consume response data to free up memory
        return;
    }
    response.setEncoding('utf8');
    var rawData = '';
    response.on('data', function (chunk) {rawData += chunk;});
    response.on('end', function () {
        try {
            console.log(JSON.parse(rawData));
        } catch (e) {
            console.log(e.message);
        }
    });
}).on('socket', function (socket) {
    socket.emit('agentRemove');
}).on('error', function (error) {
    console.log('Got error: ' + error.message);
});

//---------------------------------------------

var http = require('http');

var server = http.createServer(function (request, response) {
    var body = '';

    request.setEncoding('utf8');

    request.on('data', function (chunk) {
        body += chunk;
    });

    request.on('end', function() {
        try {
            var data = JSON.parse(body);
            response.write(typeof data);
            response.end();
        } catch (error) {
            response.statusCode = 400;
            return res.end('error: ' + error.message);
        }
    });
});

server.listen(1337);

//---------------------------------------------

var postData = querystring.stringify({msg : 'Hello World!'});

var options = {
    hostname: 'www.google.com',
    port: 80,
    path: '/upload',
    method: 'POST',
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Content-Length': Buffer.byteLength()
    }
};

var clientRequest = http.request(options,  function (response) {
    console.log(response);
    console.log(response.statusCode);
    console.log(response.statusMessage);
    console.log(response.headers);
    response.setEncoding('utf8');
    response.on('data', function (chunk) {
        console.log(chunk);
    });
    response.on('end', function () {
        console.log('No more data in response.');
    });
});

clientRequest.on('error', function (error) {
    console.log(problem with request: ' + error.message);
});

clientRequest.on('connect', function (res, socket, head) {
    console.log('got connected!');
    // make a request over an HTTP tunnel
    socket.write('GET / HTTP/1.1\r\n' +
                     'Host: www.google.com:80\r\n' +
                     'Connection: close\r\n' +
                     '\r\n');
    socket.on('data', function (chunk) {console.log(chunk.toString());});
    socket.on('end',  function () {proxy.close();});
});


clientRequest.on('upgrade', function (res, socket, upgradeHead) {
    console.log('got upgraded!');
    socket.end();
    process.exit(0);
});

clientRequest.on('response',  function (response) {});
clientRequest.on('continue',  function () {});

clientRequest.on('abort',  function () {});
clientRequest.on('aborted',  function () {});

clientRequest.on('socket',  function (socket) {});

clientRequest.setTimeout(5000, function () {});

clientRequest.abort();

clientRequest.setNoDelay(true);
clientRequest.setSocketKeepAlive(true, 1000);

clientRequest.flushHeaders();

clientRequest.write('some data', 'utf8', function () {});
clientRequest.end(postData, 'utf8', function () {});

//---------------------------------------------

var server = http.createServer(function (request, request)  {

    request.on('aborted', function () {});
    request.on('close', function () {});
    request.destroy(error);
    console.log(request.headers);
    console.log(request.rawHeaders);
    console.log(request.trailers);
    console.log(request.rawTrailers);
    console.log(request.httpVersion);
    console.log(request.socket);
    request.setTimeout(5000, function () {});
    if (request.method === 'POST') {}
    if (require('url').parse(request.url).pathname === '/path') {}

    //---------------------------------------------

    response.on('close', function () {});
    response.on('finish', function () {});
    response.setTimeout(5000, function () {});
    var contentType = response.getHeader('content-type');
    response.setHeader('Content-Type', 'text/html');
    response.removeHeader('Content-Encoding');
    response.statusCode = 404;
    response.statusMessage = 'Not found';
    response.writeHead(200, {'Content-Type': 'text/plain', 'Trailer': 'Content-MD5', 'Content-Length': Buffer.byteLength('body')});
    response.write('data', 'utf8', function () {});
    response.addTrailers({'Content-MD5': '7895bf4b8828b55ceaf47747b4bca667'});
    response.writeContinue();
    response.end('data', 'utf8', function () {});
    if (response.finished) {}
    if (response.sendDate) {}
    console.log(response.headersSent);

});
server.on('connect', function (request, socket, upgradeHead) {});
server.on('connection', function (socket ) {});
server.on('request', function (request, response) {});
server.on('upgrade', function (request, socket, upgradeHead) {});
server.on('checkContinue', function () {});
server.on('checkExpectation', function (request, response) {});
server.on('clientError', function (err, socket) {
    socket.end('HTTP/1.1 400 Bad Request');
});
server.on('close', function () {});

server.listen(handle, function () {});
server.listen('127.0.0.1:80', function () {});
server.listen(80, '127.0.0.1', backlog, function () {});

if (server.listening) {}

server.setTimeout(5000, function () {});
server.timeout = 5000;
console.log(server.timeout);

server.maxHeadersCount = 1000;
console.log(server.maxHeadersCount);

server.close(function () {});

//---------------------------------------------

var options = {
    hostname: 'encrypted.google.com',
    port: 443,
    path: '/',
    method: 'GET',
    key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'),
    cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem')
};
options.agent = new https.Agent(options);

var req = https.request(options, function (response) {
    ...
});

//---------------------------------------------

var https = require('https');

https.get('https://encrypted.google.com/', function (response) {
    console.log('statusCode:', res.statusCode);
    console.log('headers:', res.headers);
    res.on('data', function (data) {
        process.stdout.write(data);
    });
}).on('error', function (error) {
    console.error(error);
});

//---------------------------------------------

const https = require('https');

var options = {
    hostname: 'encrypted.google.com',
    port: 443,
    path: '/',
    method: 'GET'
};

var clientRequest = https.request(options, function (response) {
    console.log('statusCode:', response.statusCode);
    console.log('headers:', response.headers);
    response.on('data', function (data) {
        process.stdout.write(data);
    });
});
clientRequest.on('error', function (error) {
    console.error(error);
});
clientRequest.end();

//---------------------------------------------

var https = require('https');
var fs = require('fs');

var options = {
    key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'),
    cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem')
    // fx: fs.readFileSync('server.pfx')
};

https.createServer(options, function (req, res) {
    res.writeHead(200);
    res.end('hello world\n');
}).listen(8000);

net - Socket, connect, createConnection, createServer

var net = require('net');

var server = net.createServer(function (socket)  {
    socket.end('goodbye');
});

server.on('connection', function (socket) {});

server.on('error', function (error) {
    if (error.code == 'EADDRINUSE') {
        console.log('Address in use, retrying...');
        setTimeout(function () {
            server.close();
            server.listen(PORT, HOST);
        }, 1000);
    }
});

server.on('close', function () {});

server.on('listening', function () {});

server.listen(80, function () {
    console.log('opened server on', server.address());
});

server.listen(handle, backlog, function () {});
server.listen({host: 'localhost', port: 80, exclusive: true}, function () {});
server.listen('127.0.0.1:80', backlog, function () {});
server.listen(80, '127.0.0.1', backlog, function () {});

if (server.listening) {}

server.close(function () {});

server.ref();
server.unref();

console.log(server.maxConnections);
console.log(server.connections);
server.getConnections(function (error, count) {console.log('connections: ' + count);});

//---------------------------------------------

var net = require('net');

var server = net.createServer(function (connection) {
    console.log('client connected');
    connection.on('end', function () {
        console.log('client disconnected');
    });
    connection.write('hello');
    connection.pipe(connection);
});
server.on('error', function (error) {
    throw connection;
});
server.listen(8124, function () {
    console.log('server bound');
});

telnet localhost 8124

server.listen('/tmp/echo.sock',  function () {
    console.log('server bound');
});

nc -U /tmp/echo.sock

//---------------------------------------------

const net = require('net');

const client = net.createConnection({port: 8124}, function () {
    console.log('connected to server!');
    client.write('world!');
});
client.on('data', function (data) {
    console.log(data.toString());
    client.end();
});
client.on('end', function ()  {
    console.log('disconnected from server');
});

net.createConnection({path: '/tmp/echo.sock'}, function () {});
net.createConnection('127.0.0.1:80', function () {});
net.createConnection(80, '127.0.0.1', function () {});

//---------------------------------------------

var net = require('net');

var socket = new net.Socket({
    fd: null,
    allowHalfOpen: false,
    readable: false,
    writable: false
});

socket.on('lookup', function (error, address, family, host) {});

socket.on('timeout', function () {});

socket.on('error', function (error) {});

socket.on('connect', function () {});

socket.on('data', function (data) {});
socket.on('end', function (data) {});

socket.on('drain', function () {});

socket.on('close', function () {});

socket.setTimeout(5000, function () {});

socket.setEncoding('utf8');

socket.write('data', 'utf8', function () {});
socket.end('data', 'utf8');

console.log(socket.bufferSize);
console.log(socket.bytesRead);
console.log(socket.bytesWritten);

console.log(socket.address());
console.log(socket.localAddress);
console.log(socket.localPort);

console.log(socket.remoteFamily);
console.log(socket.remoteAddress);
console.log(socket.remotePort);

socket.connect(options, connectListener)l
socket.connect(path, connectListener)l
socket.connect(port, host, connectListener)l
if (socket.connecting) {}

socket.destroy(error);
if (socket.destroyed) {}

socket.pause();
socket.resume();

socket.setKeepAlive(true, 5000);
socket.setNoDelay(true);

socket.ref();
socket.unref();

//---------------------------------------------

var net = require('net');

var client = net.connect({port: 8124}, function () {
    console.log('connected to server!');
    client.write('world!');
});
client.on('data', function (data) {
    console.log(data.toString());
    client.end();
});
client.on('end', function () {
    console.log('disconnected from server');
});

net.connect({path: '/tmp/echo.sock'}, function () {});
net.connect('127.0.0.1:80', function () {});
net.connect(80, '127.0.0.1', function () {});

//---------------------------------------------

          if (net.isIP('127.0.0.1') === 0) {console.log('invalid IP');
} else if (net.isIP('127.0.0.1') === 4) {console.log('it is IP version 4');
} else if (net.isIP('127.0.0.1') === 6) {console.log('it is IP version 6');
}
if (net.isIPv4('127.0.0.1')) {console.log('it is IP version 4');}
if (net.isIPv6('2001:0db8:11a3:09d7:1f34:8a2e:07a0:765d')) {console.log('it is IP version 6');}

tls - TLSSocket, connect, createServer, Server

// "tls.Server" class is a subclass of "net.Server" that accepts encrypted connections using "TLS" or "SSL"

var tls = require('tls');

var server = tls.Server(function () {});

var tlsSessionStore = {};
server.on('newSession', function (sessionId, sessionData, callback) {
  tlsSessionStore[id.toString('hex')] = data;
  callback();
});
server.on('resumeSession', function (sessionId, callback) {
    callback(null, tlsSessionStore[id.toString('hex')] || null);
});

server.on('OCSPRequest', function (certificate, issuer, callback) {});

server.on('secureConnection', function (tlsSocket ) {});

server.on('tlsClientError', function (error, tlsSocket) {});

server.listen(80, '127.0.0.1', function () {
    console.log(server.address(););
});

console.log(server.connections);

server.addContext(hostname, context);

console.log(server.getTicketKeys());
server.setTicketKeys(keys);

server.close(function () {});

//---------------------------------------------

// "tls.TLSSocket" is a subclass of "net.Socket" that performs transparent encryption of written data and all required TLS negotiation

var tlsSocket = new tls.TLSSocket(socket, options);

tlsSocket.on('OCSPResponse', function (response) {});
tlsSocket.on('secureConnect', function () {});

console.log(tlsSocket.address());

tlsSocket.setMaxSendFragment(16384);

if (tlsSocket.authorized) {
    // ...
} else {
    console.log(tlsSocket.authorizationError);
}

if (tlsSocket.encrypted) {}

tlsSocket.renegotiate({rejectUnauthorized; true}, function () {});

var cipher = tlsSocket.getCipher();

console.log(tlsSocket.getEphemeralKeyInfo());
console.log(tlsSocket.getPeerCertificate(true));
console.log(tlsSocket.getProtocol());
console.log(tlsSocket.getSession());
console.log(tlsSocket.getTLSTicket());

console.log(tlsSocket.localAddress);
console.log(tlsSocket.remoteAddress);

console.log(tlsSocket.localPort);
console.log(tlsSocket.remotePort);

console.log(tlsSocket.remoteFamily);

//---------------------------------------------

var tls = require('tls');
var fs = require('fs');

var options = {
    // Necessary only if using the client certificate authentication
    key: fs.readFileSync('client-key.pem'),
    cert: fs.readFileSync('client-cert.pem'),
    // Necessary only if the server uses the self-signed certificate
    ca: [fs.readFileSync('server-cert.pem')]
};

var socket = tls.connect(8000, options, function () {
    console.log('client connected', socket.authorized ? 'authorized' : 'unauthorized');
    process.stdin.pipe(socket);
    process.stdin.resume();
});
socket.setEncoding('utf8');
socket.on('data', function (data) {
    console.log(data);
});
socket.on('end', function () {
    server.close();
});

var socket = tls.connect(80, '127.0.0.1', options, function () {});
var socket = tls.connect('127.0.0.1:80', options, function () {});
var socket = tls.connect({host: '127.0.0.1:80', port: 80, path: '/path'}, function () {});

console.log(tls.getCiphers()); // ['AES128-SHA', 'AES256-SHA', ...]
console.log(tls.DEFAULT_ECDH_CURVE);

tls.createSecureContext({
    // Necessary only if using the client certificate authentication
    key: fs.readFileSync('client-key.pem'),
    cert: fs.readFileSync('client-cert.pem'),
    // Necessary only if the server uses the self-signed certificate
    ca: [fs.readFileSync('server-cert.pem')]
});

//---------------------------------------------

var tls = require('tls');
var fs = require('fs');

var options = {
    key: fs.readFileSync('server-key.pem'),
    cert: fs.readFileSync('server-cert.pem'),
    // This is necessary only if using the client certificate authentication.
    requestCert: true,
    // This is necessary only if the client uses the self-signed certificate.
    ca: [ fs.readFileSync('client-cert.pem') ]
};

const server = tls.createServer(options, function (socket) {
    console.log('server connected', socket.authorized ? 'authorized' : 'unauthorized');
    socket.write('welcome!');
    socket.setEncoding('utf8');
    socket.pipe(socket);
});
server.listen(8000, function () {
    console.log('server bound');
});

openssl s_client -connect 127.0.0.1:8000

dgram - createSocket  

var dgram = require('dgram');

var server = dgram.createSocket('udp4');

var server = dgram.createSocket({type: 'udp4', reuseAddr: true}, function (msg, rinfo) {
    console.log('server got: ' + msg + ' from ' + rinfo.address + ':' + rinfo.port);
});
var server = dgram.createSocket('udp4' , function (msg, rinfo) {
    console.log('server got: ' + msg + ' from ' + rinfo.address + ':' + rinfo.port);
});

server.on('error', function (error) {
    console.log('server error: ' + error.stack);
    server.close();
});

server.on('message', function (msg, rinfo) {
    console.log('server got: ' + msg + ' from ' + rinfo.address + ':' + rinfo.port);
});

server.on('listening', function () {
    var address = server.address();
    console.log('server listening ' + address.address + ':' + address.port);
});

server.on('close', function () {});

server.bind(41234); // server listening 0.0.0.0:41234
server.bind(41234, function () {
    server.addMembership('127.0.0.1'); // server listening 127.0.0.1:41234
});

server.bind(80, '127.0.0.1', function () {});
server.bind({port: 80, address: '127.0.0.1', exclusive: true}, function () {});

console.log(server.address());

server.send('message', offset, length, 80, '127.0.0.1', function (error) {server.close();});

var dgram = require('dgram');
var client = dgram.createSocket('udp4');
var message = Buffer.from('Some bytes');
client.send(message, 41234, 'localhost', function (error) {
    client.close();
});

var dgram = require('dgram');
var client = dgram.createSocket('udp4');
var buf1 = Buffer.from('Some ');
var buf2 = Buffer.from('bytes');
client.send([buf1, buf2], 41234, 'localhost', function (error) {
    client.close();
});

server.addMembership(multicastAddress, multicastInterface);
socket.dropMembership(multicastAddress, multicastInterface);

server.setBroadcast(true);
server.setMulticastLoopback(true);

server.setMulticastTTL(255);
server.setTTL(1);

server.close(function () {});

server.ref();
server.unref();

HTTP server

var http = require('http');

var server = http.createServer(function (request, response) {
    response.writeHead(200, 'OK', {'Content-Type': 'text/html'});
    response.write('Hello, ');
    response.end('World!');
});

server.listen(8124, '127.0.0.1', function () {
    console.log('server is listening on 127.0.0.1:8124');
});

HTTP client

var http = require('http');

var client = http.request({host: '127.0.0.1', port: 8124}, function (response) {
    var data = '';
    response.on('data', function (chunk) {
        data += chunk;
    });
    response.on('end', function () {
       console.log(data);
    });
});

client.end();

TCP Socket server

var net = require('net');

var PORT = 8124;

// Создание сервера и прослушивание соединения сервера с клиентом
var server = net.createServer(function (connection) {
    console.log('connected');
    // Можно получать строки или буфер
    connection.on('data', function (data) {
        console.log(data + ' from client address ' + connection.remoteAddress + ' and port ' + connection.remotePort);
        connection.write('Repeating to client: ' + data);
    });
    connection.on('close', function () {
        console.log('client closed connection');
    });
}).listen(PORT);

server.on('listening', function () {
    console.log('server is listening on ' + PORT);
});

server.on('error', function (error) {
    if (error.code == 'EADDRINUSE') {
        console.warn('Address in use, retrying...');
        setTimeout(function () {
            server.close();
            server.listen(PORT);
        }, 1000);
    } else {
        console.error(error);
    }
});

TCP Socket client

var net = require('net');

var client = new net.Socket();

client.setEncoding('utf8');

// Подключение к серверу
client.connect('8124', '127.0.0.1', function () {
    console.log('connected to server');
    // Можно отправлять строки или буфер
    client.write('Enter text, that client will send to server, and press "Enter".');
});

// Полученные данные из консоли командной строки отправляются серверу
process.stdin.on('data', function (data) {
    client.write(data);
});

// Возвращаемые данные от сервера выводятся на консоль командной строки
client.on('data', function (data) {
    console.log(data);
});

// При закрытии соединения с сервером выводим сообщение
client.on('close', function() {
    console.log('connection closed');
});

UDP server

var dgram = require('dgram');

var server = dgram.createSocket('udp4');

server.on('listening', function () {
    var address = server.address();
    console.log('server is listening at ' + address.address + ':' + address.port);
});

server.on('message', function (message, rinfo) {
    console.log('server got: ' + message + ' from client ' + rinfo.address + ':' + rinfo.port);
});

server.on('error', function (error) {
    console.log('server error:' + error.stack);
    server.close();
});

server.bind(8124, '127.0.0.1', function () {
    console.log('server is listening on 127.0.0.1:8124');
});

UDP client

var dgram = require('dgram');

var client = dgram.createSocket('udp4');

client.on('close', function () {
    process.exit(0);
});

process.stdin.on('data', function (data) {
    console.log(data.toString('utf8'));
    client.send(data, 0, data.length, 8124, '127.0.0.1', function (error, bytes) {
        if (error) {
            console.error('error: ' + error);
        } else {
            console.log('successful');
        }
        client.close();
    });
});

Комментариев нет:

Отправить комментарий