LoginSignup
6
10

More than 5 years have passed since last update.

JavaScript(Node.js)初心者事始めメモ

Last updated at Posted at 2016-10-16

背景

会社の研修の課題をJavaScrip(Node.js)で提出せよと言われましたが、研究・開発が主な業務でフロントエンドエンジニアではない自分は正直使ったことがないので四苦八苦しています。
いい機会なので勉強がてらメモを残します。
※課題提出はきっと間に合わぬ

環境構築

OS:Mac OSX EI Captian
Memory: 4 GB 1600 MHz DDR3

Node.jsのdownloadからinstallまで

wget -N http://nodejs.org/dist/node-latest.tar.gz
tar xzvf node-latest.tar.gz
cd node-v[バージョン番号]
./configure
make
sudo make install

参考:Node.js入門

./cofigure の所でもし

  File "./configure", line 486
    except OSError, e:
                  ^
SyntaxError: invalid syntax

と出たらpythonのバージョンをpython -Vで確認して、3系になっているようでしたら pyenv global などで2系にしてみてください。私の環境ではそれで通りました。

超基本コマンドメモ

当たり前すぎるのかあまり端的な記述がない。

  • 実行*
node xxx.js
  • 外部ライブラリの利用*
npm install xxx@x.x.x ※@以下はバージョン情報オプション

でインストール後、

var ex_lib = require('xxx')
  • コンソール表示
console.log('hoge')
  • 標準入力(2016/10/18追記)
var reader = require('readline').createInterface({
    input: process.stdin,
    output: process.stdout
});
reader.on('line', function (line) {
  console.log(line);
});
reader.on('close', function () {
  console.log('close')
});
  • コメントアウト
//一行だけコメント
/*複数行
 コメントアウト*/

*直下のコードはコンソールに打ち込むコマンド、それ以外はxxx.jsに書き込むプログラムコード

Bufferについて

外部ライブラリを実行した戻り値としてBufferが返ってきていたのですが、エンコードされた値の取り出し方がわからずにずっと、

console.log(buff)
 <Buffer 31 f3 0d db cb 1b f8 44 65 76 f0 e6 4a a4 c8 8a 9f 05 5e 3c>

のような表示のさせ方をしていました。2日程悩んでいたのですが、これは16進数で表示された文字列とのことで、以下のようにすればStringで取り出せます。

console.log(buff.toString('hex'))
 31f30ddbcb1bf8446576f0e64aa4c88a9f055e3c

参考:Node.js v0.11.11 マニュアル & ドキュメンテーション

以下、随時更新予定

6
10
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
10