0
0

More than 3 years have passed since last update.

nodeコマンド(non-blockngとblockingについてメモ)

Posted at

コマンドライン上で操作

node.jsではブラウザなどを使用せずにコマンドライン上で操作ができる

# コマンドライン上での操作開始を宣言
$ node

# この状態で処理を書くと実行される
> console.log('hello world')  # 出力結果: hello world

# 終了する
> .exit

jsファイルから実行

jsファイルsample.jsを作成し、処理を実行させる

# コマンドライン上でjsファイルの処理開始を宣言
$ node sample.js

non-blockngとblockingな書き方

  • nodeはメインのスレッドが1つであるため、処理がブロックされるような書き方はnodeの処理の速さの特徴を殺してしまうためやめるべきである
  • setTimeoutなどのタイマー処理やデータベースへのアクセス、ファイルの書き込みといった命令は処理に時間を要するため、次の命令をブロックしないように書く必要がある

そこで、non-blockingな書き方を採用し、時間がかかりそうな関数はcallback関数で実装することが望ましい

non-blockingな書き方

次の処理をブロックしない書き方のこと

setTimeout(function() {
  console.log('hello');
}, 1000);
conosole.log('world')

setTimeout内の関数をcallback関数という
setTimeoutの内の処理を待たずに次の処理が実行される

blockingな書き方

var start = new Data().getTime();
while (new Data().getTime() < start + 1000);
console.log('world');
0
0
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
0
0