puppeteerを入れよう

$ npm install –save puppeteer

main.js

const puppeteer = require('puppeteer');
const url = 'http://www.google.co.jp';

(async function(){
	const browser = await puppeteer.launch();
	const page = await browser.newPage();
	const response = await page.goto(url);

	await browser.close();
})();

[vagrant@localhost ~]$ node main.js
(node:9969) UnhandledPromiseRejectionWarning: Error: Failed to launch chrome!
/home/vagrant/node_modules/puppeteer/.local-chromium/linux-662092/chrome-linux/chrome: error while loading shared libraries: libXss.so.1: cannot open shared object file: No such file or directory

TROUBLESHOOTING: https://github.com/GoogleChrome/puppeteer/blob/master/docs/troubleshooting.md

at onClose (/home/vagrant/node_modules/puppeteer/lib/Launcher.js:342:14)
at Interface.helper.addEventListener (/home/vagrant/node_modules/puppeteer/lib/Launcher.js:331:50)
at Interface.emit (events.js:187:15)
at Interface.close (readline.js:379:8)
at Socket.onend (readline.js:157:10)
at Socket.emit (events.js:187:15)
at endReadableNT (_stream_readable.js:1094:12)
at process._tickCallback (internal/process/next_tick.js:63:19)
(node:9969) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:9969) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

あれれ

SyntaxError: Use of const in strict mode.

JavaScript has introduced const and let in ECMAScript 2015, which is relatively recent. This is enabled by default in Node.js since Node.js 4.x.

$ git clone git://github.com/creationix/nvm.git ~/.nvm
$ source ~/.nvm/nvm.sh
$ nvm help
$ nvm ls-remote
[root@localhost vagrant]# nvm install v8.16.0
Downloading and installing node v8.16.0…
Downloading https://nodejs.org/dist/v8.16.0/node-v8.16.0-linux-x64.tar.xz…
######################################################################## 100.0%
Computing checksum with sha256sum
Checksums matched!
Now using node v8.16.0 (npm v6.4.1)
[root@localhost vagrant]# node -v
v8.16.0

[root@localhost test]# node chromeTest.js
/home/vagrant/local/app/test/chromeTest.js:3
var By = webdriver.By;
^

ReferenceError: webdriver is not defined
at Object. (/home/vagrant/local/app/test/chromeTest.js:3:10)
at Module._compile (module.js:653:30)
at Object.Module._extensions..js (module.js:664:10)
at Module.load (module.js:566:32)
at tryModuleLoad (module.js:506:12)
at Function.Module._load (module.js:498:3)
at Function.Module.runMain (module.js:694:10)
at startup (bootstrap_node.js:204:16)
at bootstrap_node.js:625:3

What…

Error: EACCES

[vagrant@localhost test]$ sudo chmod 777 /usr/local/lib;

[vagrant@localhost test]$ sudo npm install -g bower
npm http GET https://registry.npmjs.org/bower
npm http 200 https://registry.npmjs.org/bower
npm WARN deprecated bower@1.8.8: We don’t recommend using Bower for new projects. Please consider Yarn and Webpack or Parcel. You can read how to migrate legacy project here: https://bower.io/blog/2017/how-to-migrate-away-from-bower/
npm http GET https://registry.npmjs.org/bower/-/bower-1.8.8.tgz
npm http 200 https://registry.npmjs.org/bower/-/bower-1.8.8.tgz
/usr/bin/bower -> /usr/lib/node_modules/bower/bin/bower
npm WARN unmet dependency /usr/lib/node_modules/block-stream requires inherits@’~2.0.0′ but will load
npm WARN unmet dependency undefined,
npm WARN unmet dependency which is version undefined
npm WARN unmet dependency /usr/lib/node_modules/fstream requires inherits@’~2.0.0′ but will load
npm WARN unmet dependency undefined,
npm WARN unmet dependency which is version undefined
npm WARN unmet dependency /usr/lib/node_modules/fstream-ignore requires inherits@’2′ but will load
npm WARN unmet dependency undefined,
npm WARN unmet dependency which is version undefined
npm WARN unmet dependency /usr/lib/node_modules/fstream-npm requires inherits@’2′ but will load
npm WARN unmet dependency undefined,
npm WARN unmet dependency which is version undefined
npm WARN unmet dependency /usr/lib/node_modules/glob requires inherits@’2′ but will load
npm WARN unmet dependency undefined,
npm WARN unmet dependency which is version undefined
npm WARN unmet dependency /usr/lib/node_modules/npmconf requires inherits@’~2.0.0′ but will load
npm WARN unmet dependency undefined,
npm WARN unmet dependency which is version undefined
npm WARN unmet dependency /usr/lib/node_modules/tar requires inherits@’2′ but will load
npm WARN unmet dependency undefined,
npm WARN unmet dependency which is version undefined
bower@1.8.8 /usr/lib/node_modules/bower

Node.jp update

[vagrant@localhost test]$ node –version
v0.10.48
[vagrant@localhost test]$ npm –version
1.3.6
[vagrant@localhost test]$ n –latest
-bash: n: コマンドが見つかりません

There is a handy version control tool, n, which lets you check and update versions.

[vagrant@localhost test]$ npm install -g n
npm http GET https://registry.npmjs.org/n
npm http GET https://registry.npmjs.org/n
npm http GET https://registry.npmjs.org/n
npm ERR! Error: CERT_UNTRUSTED
npm ERR! at SecurePair. (tls.js:1430:32)
npm ERR! at SecurePair.emit (events.js:92:17)
npm ERR! at SecurePair.maybeInitFinished (tls.js:1029:10)
npm ERR! at CleartextStream.read [as _read] (tls.js:521:13)
npm ERR! at CleartextStream.Readable.read (_stream_readable.js:341:10)
npm ERR! at EncryptedStream.write [as _write] (tls.js:418:25)
npm ERR! at doWrite (_stream_writable.js:226:10)
npm ERR! at writeOrBuffer (_stream_writable.js:216:5)
npm ERR! at EncryptedStream.Writable.write (_stream_writable.js:183:11)
npm ERR! at write (_stream_readable.js:602:24)
npm ERR! If you need help, you may report this log at:
npm ERR!
npm ERR! or email it to:
npm ERR!

npm ERR! System Linux 2.6.32-754.3.5.el6.x86_64
npm ERR! command “node” “/usr/bin/npm” “install” “-g” “n”
npm ERR! cwd /home/vagrant/local/app/test
npm ERR! node -v v0.10.48
npm ERR! npm -v 1.3.6
npm ERR!
npm ERR! Additional logging details can be found in:
npm ERR! /home/vagrant/local/app/test/npm-debug.log
npm ERR! not ok code 0

The reason is that SSL key validation is performed on the https registry, so once this setting is set to false, npm install will succeed.

vagrant@localhost test]$ npm config set strict-ssl false

[vagrant@localhost test]$ npm install -g n
npm http GET https://registry.npmjs.org/n
npm http 200 https://registry.npmjs.org/n
npm http GET https://registry.npmjs.org/n/-/n-4.1.0.tgz
npm http 200 https://registry.npmjs.org/n/-/n-4.1.0.tgz
npm ERR! Error: EACCES, mkdir ‘/usr/lib/node_modules/n’
npm ERR! { [Error: EACCES, mkdir ‘/usr/lib/node_modules/n’]
npm ERR! errno: 3,
npm ERR! code: ‘EACCES’,
npm ERR! path: ‘/usr/lib/node_modules/n’,
npm ERR! fstream_type: ‘Directory’,
npm ERR! fstream_path: ‘/usr/lib/node_modules/n’,
npm ERR! fstream_class: ‘DirWriter’,
npm ERR! fstream_stack:
npm ERR! [ ‘/usr/lib/node_modules/fstream/lib/dir-writer.js:36:23’,
npm ERR! ‘/usr/lib/node_modules/mkdirp/index.js:37:53’,
npm ERR! ‘Object.oncomplete (fs.js:108:15)’ ] }
npm ERR!
npm ERR! Please try running this command again as root/Administrator.

npm ERR! System Linux 2.6.32-754.3.5.el6.x86_64
npm ERR! command “node” “/usr/bin/npm” “install” “-g” “n”
npm ERR! cwd /home/vagrant/local/app/test
npm ERR! node -v v0.10.48
npm ERR! npm -v 1.3.6
npm ERR! path /usr/lib/node_modules/n
npm ERR! fstream_path /usr/lib/node_modules/n
npm ERR! fstream_type Directory
npm ERR! fstream_class DirWriter
npm ERR! code EACCES
npm ERR! errno 3
npm ERR! stack Error: EACCES, mkdir ‘/usr/lib/node_modules/n’
npm ERR! fstream_stack /usr/lib/node_modules/fstream/lib/dir-writer.js:36:23
npm ERR! fstream_stack /usr/lib/node_modules/mkdirp/index.js:37:53
npm ERR! fstream_stack Object.oncomplete (fs.js:108:15)
npm ERR!
npm ERR! Additional logging details can be found in:
npm ERR! /home/vagrant/local/app/test/npm-debug.log
npm ERR! not ok code 0

This time with a different error, it says “Error: EACCES”.

node.jsを使ってvue-cliを入れよう

まずnpmを使えるようにします。
[vagrant@localhost python]$ source ~/.nvm/nvm.sh
[vagrant@localhost python]$ nvm ls
-> v10.7.0
system
default -> 10.7.0 (-> v10.7.0)
node -> stable (-> v10.7.0) (default)
stable -> 10.7 (-> v10.7.0) (default)
iojs -> N/A (default)
unstable -> N/A (default)
lts/* -> lts/carbon (-> N/A)
lts/argon -> v4.9.1 (-> N/A)
lts/boron -> v6.14.3 (-> N/A)
lts/carbon -> v8.11.3 (-> N/A)
[vagrant@localhost python]$ nvm use 10.7.0
Now using node v10.7.0 (npm v6.1.0)
[vagrant@localhost python]$ node -v
v10.7.0
[vagrant@localhost python]$ npm -v
6.1.0

続いてvue-cliをインストール
[vagrant@localhost python]$ npm install -g vue-cli
npm WARN deprecated coffee-script@1.12.7: CoffeeScript on NPM has moved to “coffeescript” (no hyphen)
/home/vagrant/.nvm/versions/node/v10.7.0/bin/vue -> /home/vagrant/.nvm/versions/node/v10.7.0/lib/node_modules/vue-cli/bin/vue
/home/vagrant/.nvm/versions/node/v10.7.0/bin/vue-init -> /home/vagrant/.nvm/versions/node/v10.7.0/lib/node_modules/vue-cli/bin/vue-init
/home/vagrant/.nvm/versions/node/v10.7.0/bin/vue-list -> /home/vagrant/.nvm/versions/node/v10.7.0/lib/node_modules/vue-cli/bin/vue-list
+ vue-cli@2.9.6
added 253 packages from 220 contributors in 90.959s

2.9.6ですね。
[vagrant@localhost python]$ vue –version
2.9.6

pugを使いたい node.jsをupdate

pugを使いたい。で、node.jsのvをみる。
[vagrant@localhost python]$ node -v
v0.10.48
[vagrant@localhost python]$ npm -v
1.3.6

あれ、古くないか?

https://nodejs.org/ja/download/releases/
最新だと、10.7.0ですね。0.10.48ってどういうことだ?

[vagrant@localhost python]$ git clone git://github.com/creationix/nvm.git ~/.nvm
Initialized empty Git repository in /home/vagrant/.nvm/.git/
remote: Counting objects: 7182, done.
remote: Compressing objects: 100% (11/11), done.
remote: Total 7182 (delta 10), reused 17 (delta 8), pack-reused 7163
Receiving objects: 100% (7182/7182), 2.22 MiB | 439 KiB/s, done.
Resolving deltas: 100% (4517/4517), done.
[vagrant@localhost python]$ source ~/.nvm/nvm.sh
[vagrant@localhost python]$ nvm ls

-> system
iojs -> N/A (default)
node -> stable (-> N/A) (default)
unstable -> N/A (default)
[vagrant@localhost python]$ nvm ls-remote

[vagrant@localhost python]$ nvm install 10.7.0

[vagrant@localhost python]$ nvm use 10.7.0
Now using node v10.7.0 (npm v6.1.0)
[vagrant@localhost python]$ node -v
v10.7.0

はああああああああああ? v10.7.0になりました。なんだこりゃ。

[vagrant@localhost python]$ npm -v
6.1.0

はあああああああああああああああああ?

node.jsが入っているのに、npmコマンドが使えない時

# node server.js
module.js:340
Cannot find module ‘lodash’

npm install lodash –save で、npmインストールしようとしたが、できない。

$ sudo yum groupinstall 'Development tools'
$ wget http://nodejs.org/dist/v0.12.0/node-v0.12.0.tar.gz
$ tar xvf node-v0.12.0.tar.gz
$ cd node-v0.12.0/
$ ./configure --prefix=/usr/local
$ make
$ sudo make install

ほぅ

Node.js Socket.IOによるチャットルーム作成

まず、soket.ioのフォルダを作り、nmpでSocket.ioをインストールします。

[vagrant@localhost ~]$ mkdir socket.io
[vagrant@localhost ~]$ cd socket.io
[vagrant@localhost socket.io]$ node -v
v0.10.46
[vagrant@localhost socket.io]$ npm install socket.io

socket.io
socket.ioとは、ブラウザ・node.jsのライブラリで、Websocketの技術を使っています。
Socket.IO is a JavaScript library for realtime web applications. It enables realtime, bi-directional communication between web clients and servers. It has two parts: a client-side library that runs in the browser, and a server-side library for node.js. Both components have a nearly identical API. Like node.js, it is event-driven.
Socket.IO primarily uses the WebSocket protocol with polling as a fallback option, while providing the same interface. Although it can be used as simply a wrapper for WebSocket, it provides many more features, including broadcasting to multiple sockets, storing data associated with each client, and asynchronous I/O.
It can be installed with the npm tool.

では、app.jsとindex.htmlでサーバーサイドとクライアントサイドのウェブソケットを実装してみましょう。
app.js

var app = require('http').createServer(handler),
  io = require('socket.io').listen(app),
  fs = require('fs')
app.listen(1337);
function handler(req, res){
  fs.readFile(__dirname + '/index.html', function(err, data){
    if (err){
      res.writeHead(500);
      return res.end('Error');
    }
    res.writeHead(200);
    res.write(data);
    res.end();
  })
}
io.sockets.on('connection', function(socket){
  socket.on('emit_from_client', function(data){
    // console.log(data);
   // 接続しているソケットのみ
    //  socket.emit('emit_from_server', 'hello from server: ' + data);
   // 接続しているソケット以外全部
    // socket.broadcast.emit('emit_from_server', 'hello from server: ' + data);
    // 接続しているソケット全部
    // socket.client_name = data.name;
    //   io.sockets.emit('emit_from_server', '[' + socket.client_name + '] : ' + data.msg);
    socket.join(data.room);
    socket.emit('emit_from_server', 'you are in ' + data.room);
    socket.broadcast.to(data.room).emit('emit_from_server', data.msg);
  });
});

index.html

<!doctype html>
<html lang="ja">
<head>
  <meta charset="utf-8">
  <title>socket.ioの練習</title>
</head>
<body>
  <form id="myForm">
    <select id="rooms">
      <option value="room-1">Room 1</option>
      <option value="room-2">Room 2</option>
    </select>
    <input type="text" id="msg">
    <input type="submit" value="Send!">
  </form>
  <ul id="logs"></ul>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
  <script src="/socket.io/socket.io.js"></script>
  <script>
  $(function(){
    var socket = io.connect();
    // emit: イベントを発信している
    // on: イベントを待ち受けている
    $('#myForm').submit(function(e){
      e.preventDefault();
      socket.json.emit('emit_from_client', {
        msg: $('#msg').val(),
        room: $('#rooms').val()
      });
      $('#msg').val('').focus();
    });
    socket.on('emit_from_server', function(data){
      $('#logs').append($('<li>').text(data));
    });
  });
  </script>
</body>
</html>

ブラウザを三つ立ち上げて、ローカル環境でテストしてみてください。
%e7%84%a1%e9%a1%8c

Node.jsでWebサーバーを作ってみよう

server.js

var http = require('http');
var server = http.createServer();
server.on('request', function(req, res){
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.write('hello world');
  res.end();
});
server.listen(1337, '192.168.33.10');
console.log("server listening ...");
[vagrant@localhost nodejs]$ node server.js
server listening ...

ブラウザ
%e7%84%a1%e9%a1%8c

Node.js ノンブロッキング処理

Node.jsのノンブロッキング処理を見てみましょう。下記のように、コールバック関数を実装すれば、次の処理をブロックしませんの、”world”を先にwriteします。

hello.js

setTimeout(function(){
  console.log("hello");
}, 1000);
console.log("world");
[vagrant@localhost nodejs]$ node hello.js
world
hello

コールバックの仕組みですね。
/*
Node is all about non-blocking, asynchronous architecture. This means any activity taking a long time to finish, such as file access, network communication, and database operations, are requested and put aside until the results are ready and returned via a callback function. Instead of asking to read a file and waiting for the operating system to come back with a file handler or buffer, the a callback function is invoked when the operation is completed, freeing the server to handle additional requests.
*/