Use "coffee" instead of "node" command in production
I have an app.js that is running express.js.
I wanna convert the code to coffeescript and thought about to create a app.coffee that I compile to app.js so I can run it with "node app.js".
But then it hit me that I could just write that file in app.coffee and run it with "coffee app.coffee".
开发者_JAVA百科Is this a better way? Can I run the server with "coffee" in production?
Yes you can use coffee command in production. I use it.
I can see two reasons why you would want to use app.js wrapper.
- You want to use local installation of CoffeeScript. (different versions between apps)
- You want to use the default npm start to launch your server :) See npm help scripts
Oh, and you don't need compile it. You can use a wrapper like this which compiles the coffee file transparently:
server.js:
require('coffee-script').register();
require("./yourcoffeeapp.coffee");
This wrapper technique is especially useful if you want to use CoffeeScript in some hosted environments that does not directly support the CoffeeScript command. Such as Cloud 9 IDE. No need to fiddle with compiled js-files.
I upvoted Epeli's answer, which is clear and excellent—using a .js "wrapper" rather than the coffee
command saves you from potential path headaches—but since this is a subjective question, let me throw in a contrary opinion.
Many CoffeeScripters, myself included, recommend compiling non-trivial Node apps to JS before deployment. It's not hard—look at Sam Stephenson's node-coffee-project template, which includes a Cakefile that makes compiling and testing a breeze.
One major reason for doing this is that Node stack traces give line numbers that refer to the compiled JavaScript, not the original CoffeeScript. So when errors are recorded in your server logs, it's nice to be able to look at the corresponding code right on the server.
Another advantage to compiling to JS is that it lets you work with more tools on the server—many Node debuggers, testing frameworks, and amazing goodies like cluster like to operate directly on .js files.
Getting a good compilation setup for your project takes some work, but I think you'll find it worthwhile.
I prefer to create main.js like this:
require("coffee-script");
require('./yourcoffeeapp');
And yourcoffeeapp.coffee like this:
http = require 'http'
on_request = (req, res) =>
res.writeHead 200, {'Content-Type': 'text/plain'}
res.end "Hello World\n"
server = http.createServer on_request
server.listen 1337, "127.0.0.1"
精彩评论