Meteor には REPL(Read-Eval-Print-Loop:対話型実行環境) が標準で付いています(v1.0.2以降)。
Meteor サーバー側の変数やコレクションの内容を確認したり、ドキュメント操作したり、コードをサクッと試したい時に役立ちます。
Meteor REPL (shell) 基本操作
REPLの起動
Meteor アプリケーションが起動している状態で、別のターミナルウィンドウを開いて、Meteor プロジェクトのディレクトリ内で以下のコマンドを実行すると REPL が起動します。
bash$
meteor shell
実行結果
Welcome to the server-side interactive shell!
Tab completion is enabled for global variables.
Type .reload to restart the server and the shell.
Type .exit to disconnect from the server and leave the shell.
Type .help for additional help.
>
REPLの終了
>
.exit
Meteor 再起動(reload)
>
.reload
ヘルプ表示
>
.help
実行結果
.break Terminate current command input and display new prompt
.clear Alias for .break
.exit Disconnect from server and leave shell
.help Show this help information
.load Load JS from a file into the REPL session
.reload Restart the server and the shell
.save Save all evaluated commands in this REPL session to a file
いろいろ試してみる
環境の確認
> Meteor.isServer
true
> Meteor.isClient
false
> process.env.ROOT_URL
'http://localhost:3000/'
ドキュメント操作例
### Mongoコレクションの作成
> Articles = new Mongo.Collection("articles")
{ _makeNewID: [Function],
_transform: null,
...
trackable: [Function] }}
### ドキュメントの追加
> Articles.insert({title: "Hello, World!", content: "This is example!"})
'3LjiwRMKjEnCDB9FQ'
### ドキュメント数取得
> Articles.find().count()
1
### ドキュメントの取得
> var article = Articles.findOne()
> article
{ _id: '3LjiwRMKjEnCDB9FQ',
title: 'Hello, World!',
content: 'This is example!' }
### ドキュメントの更新
> Articles.update({_id: article._id}, {$set: {title: "Hello, Meteor!"}})
1
> var article2 = Articles.findOne(article._id)
> article2
{ _id: '3LjiwRMKjEnCDB9FQ',
title: 'Hello, Meteor!',
content: 'This is example!' }
### ドキュメントの削除
> Articles.remove(article2._id)
1
> Articles.count()
0
便利ですね。
Q&A
Q1. クライアントサイドで REPL を起動するには?
A1. ブラウザで Meteor アプリケーションにアクセスし、「要素の検証」でWebインスペクタを起動してください。
WebインスペクタがREPLの役割を持っています。
Q2. meteor shell を実行したら「Server unavailable (waiting to reconnect)」とでます
A2. Meteor アプリケーションに meteor shell が接続できていない状態です。
別のターミナルウィンドウを開いて meteor アプリケーションを起動してください。
bash$
# ターミナル1: Meteor アプリケーション起動
meteor
# ターミナル2: (別のターミナルウィンドウで) REPL 起動
meteor shell