Node.js

October 14, 2017

nodejs

Node.js について

負荷計測

Feature

NPM

$ 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

var fs = require('fs')

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

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

Events(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

# 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

Express (Web)

# mkdir express-tutorial
# cd express-tutorial/
# npm init
# npm install --save express express-generator
# ./node_modules/express-generator/bin/express-cli.js sampleapp
# cd sampleapp && npm install

# export PORT=8080
# npm start