fox
fox

Reputation: 16536

trying to get coffeescript to compile correctly to javascript for node server

I'm working my way through a book on node.js, but I'm attempting to learn it in coffeescript rather than javascript.

Currently attempting to get some coffeescript to compile to this js as part of a routing demonstration:

var http = require('http'),
      url = require('url');

  http.createServer(function (req, res) {
    var pathname = url.parse(req.url).pathname;

    if (pathname === '/') {
        res.writeHead(200, {
        'Content-Type': 'text/plain'
      });
      res.end('Home Page\n')
    } else if (pathname === '/about') {
        res.writeHead(200, {
        'Content-Type': 'text/plain'
      });
      res.end('About Us\n')
    } else if (pathname === '/redirect') {
        res.writeHead(301, {
        'Location': '/'
      });
      res.end();
     } else {
        res.writeHead(404, {
        'Content-Type': 'text/plain'
      });
      res.end('Page not found\n')
    }
  }).listen(3000, "127.0.0.1");
  console.log('Server running at http://127.0.0.1:3000/'); 

Here's my coffeescript code:

http = require 'http'
url  = require 'url'
port = 3000
host = "127.0.0.1"

http.createServer (req, res) ->
    pathname = url.parse(req.url).pathname

    if pathname == '/'
        res.writeHead 200, 'Content-Type': 'text/plain'
        res.end 'Home Page\n'

    else pathname == '/about'
        res.writeHead 200, 'Content-Type': 'text/plain'
        res.end 'About Us\n'

    else pathname == '/redirect'
        res.writeHead 301, 'Location': '/'
        res.end()

    else
        res.writeHead 404, 'Content-Type': 'text/plain'
        res.end 'Page not found\n'

.listen port, host

console.log "Server running at http://#{host}:#{port}/"

The error that I'm getting back is:

helloworld.coffee:14:1: error: unexpected INDENT
        res.writeHead 200, 'Content-Type': 'text/plain'
^^^^^^^^

which makes me think that there's something wrong with the way that I have the if...else logic set up; it also looks, when I compile, like it might be trying to return the res.end statement rather than adding it as a second function to run.

Any thoughts why this might be happening, and how to repair my code?

Upvotes: 0

Views: 103

Answers (2)

cvb
cvb

Reputation: 337

Change your else to else if except last, it complaint on res.writeHead 200, 'Content-Type': 'text/plain' because you already have expression after first else - else pathname == '/about'

Upvotes: 3

Neophile
Neophile

Reputation: 1519

This is purely a tabs-vs-spaces issue. Make sure that ur editor does not convert spaces to tabs if it does that. Also, go through your code with the cursor and make sure it doesn't jump over blank areas. The issue is that while normal editors see a tab as equivalent to two or four spaces, coffeescript sees it as one space, so the indentation gets messed up.

Upvotes: 1

Related Questions