LoginSignup
15
15

More than 5 years have passed since last update.

CoffeeScriptでNode.js+Expressを今更ながら始めて見た。

Posted at

モチベーション

なんとなく避けてきた感があったのですが笑
最近、周りでCoffeeScript使いが増えて来ていて、めちゃ進められるので今更ながらやってみます。

普段はNode.jsを書いているのでNode.jsをCoffeeScriptで記述していきます。
Node.js+CoffeeScriptといっても調べてるとやはりexpress3系の記事がまだ多いですね。

準備

インストール

  • 普段Node.jsを使っている人なら以下のコマンドでインストール出来ます。
$ npm i -g coffee-script

今回の環境

  • Node.js: v0.10.35 (←アップデートしてみた)
  • CoffeeScript: v1.8.0
  • express: v4.10.6

実装

とりあえずexpressをインストールしておきます。

$ npm i express
  • メインのapp.coffeeを記述
app.coffee
app = require('express')()
http = require('http').Server(app)
port = 3000

app.get '/', (req, res) ->
  res.sendfile 'coffeeTest.html'

http.listen port, ->
  console.log "listening on *:", port
  • 表示するhtmlファイルを作る。
$ echo 'hello coffee' > coffeeTest.html

実行

$ coffee app.coffee
listening on *: 3000
express deprecated res.sendfile: Use res.sendFile instead app.coffee:11:16
  • http//localhost:3000 にアクセスして確認

まとめ

かなりカンタンに書けますね。
毎回コンパイルする必要があるかと思っていたのですが、coffeeコマンドで直接Node.jsを実行出来たんですね。
もっと応用出来るようにCoffeeScriptで記述頑張ってみます。

比較(蛇足)

  • 元にしたapp.js
app.js
var app = require('express')();
var http = require('http').Server(app);
var port = 3000

app.get('/', function(req, res){
  res.sendfile('coffeeTest.html');
});

http.listen(port, function(){
  console.log('listening on *:',port);
});
  • CoffeeScript(app.coffee)からコンパイルしたapp.js
// Generated by CoffeeScript 1.8.0
(function() {
  var app, http, port;

  app = require('express')();

  http = require('http').Server(app);

  port = 3000;

  app.get('/', function(req, res) {
    return res.sendfile('coffeeTest.html');
  });

  http.listen(port, function() {
    return console.log("listening on *:", port);
  });

}).call(this);

returnは自動的に追記されるっぽいですね。
callメソッドについてイマイチ理解しきれて無いのですが、即時関数な呼び方っぽいですね。

即時関数をcall(this)で呼ぶことについて
この辺詳しく解説してくれる人がいるとうれしいです苦笑

15
15
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
15
15