Node.js

Feature

  • Non-Blocking(Asynchronous and Event Driven)
    • callback, parallel disk access
    • これまでの言語はWebサーバをマルチスレッドで動かすことで大量アクセスを捌いていた
    • マルチスレッドといってもスレッド数には限界があった(C10K問題)
    • Node.jsはcallback呼び出しによりI/Oによるブロッキングを受けないようにしシングルスレッドで大量アクセスを捌けるようにした
    • JavaScriptのAjaxをサーバ側にも拡張している
  • Event Loop
    • callback関数の呼び出しをリッスンして待つ
  • V8 JavaScript Engine(Google Chrome) is very fast

NPM

  • Node Package Manager(online repositories)
$ npm install (install all the modules in package.json)
$ npm install --save (add the module dependency to package.json)
$ npm install <Module Name>
$ npm install <Module Name> -g (dependency globally)

File System

  • File I/O require(“fs”)
var fs = require("fs");

// Synchronous read
var data = fs.readFileSync("input.txt");

// Asynchronous read
fs.readFileSync("input.txt", function(err, data){});

Events(Event Driven)

  • Node.js follows event-driven
var event = require('events');
const myEmitter = new event.EventEmitter();

fs.readFile('test1.txt', (err, data) => {
    console.log(data.toString());
    myEmitter.emit('readFile');
});

myEmitter.on('readFile', () => {
    console.log('Read Event Occurred');
});

Docker

  • use docker
# docker pull node:6.11.4-alpine
# docker run -itd -v /opt/docker-node:/work -p 8080:8080 node:6.11.4-alpine /bin/sh
# docker exec -it <Container ID> /bin/sh

# docker run -it node:6.11.4-alpine /bin/sh
# docker run -itd node:6.11.4-alpine /bin/sh (run background)

# node -v
v6.11.4

Test

# mkdir test
# npm init
# npm install --save-dev istanbul mocha power-assert intelli-espower-loader
# vi package.json
...
  "scripts": {
    "test": "node ./node_modules/mocha/bin/mocha --recursive -R spec",
    "test-cov": "node ./node_modules/istanbul/lib/cli.js cover _mocha -- --recursive -R spec"
  },
...

# cat hello.js
console.log(hi("hello"));


function hi(a) {
    return a;
}

function ya(a) {
    return a;
}

module.exports.hi = hi;
module.exports.ya = ya;

# cat test/hello.test.js
'use strict';

const assert = require('power-assert');
const myModule = require('../hello');

describe('Sample Test', function() {
    describe('1. Hello test', function() {
        it('hello', function() {
            assert.equal(myModule.hi('hello!'), 'hello!')
        });
    });
});

# npm run test-cov
comments powered by Disqus