Global variable is not updated

I'm new to coffeescript. And I fell into the pit of the JavaScript's variable scope.

I'm trying to develop simple console script with node.js, no classes (yet), minimum functional programming sugar (yet). Here it goes:

fs      = require 'fs'
code    = "test"

fs.readFile 'COD99000430.TXT', (err, contents) ->
    code = contents.toString()

console.log code

it compiles to following JavaScript:

// Generated by CoffeeScript 1.3.3
(function() {
  var code, fs;

  fs = require('fs');

  code = "test";

  fs.readFile('COD99000430.TXT', function(err, contents) {
    return code = contents.toString();
  });

  console.log(code);

}).call(this);

The issue is that after running that code console shows only word test, which is obviously initial value of the code variable. But I expect to see contents of the COD99000430.TXT file. And actually I can see it, if i put console.log code inside of the scope of the anonymous callback function in the fs.readFile call.

I've look at coffieescript documentation and there exactly the same case was described. But for some reason it does not work for me.

I'm using node.js version 0.8.2 on Windows 7, coffeescript version 1.3.3.

Is it possible to have "global script" variable in my case? How I can achieve this via coffeescript?

The comments on your question are correct, I just thought I'd provide some working code.

Example 1: Simply log the file contents in the fs.readFile callback.

fs = require 'fs'

fs.readFile 'COD99000430.TXT', (err, contents) ->
  console.log contents.toString()

Example 2: Factor the file processing code into a function and provide a callback to print the contents.

fs = require 'fs'

processFile = (filename, callback) ->
  fs.readFile filename, (err, contents) ->
    callback contents.toString()

processFile 'COD99000430.TXT', (data) -> console.log data

I modified your code a bit so I could get it running in jsfiddle (had to ditch node since it isn't installed on this machine). I think what you need to is change the readFile line to be a function, then call the function later.

code = "test"

read = (err, contents) ->
    code = "XZY".toString()

console.log code
alert(code)

code = read()
alert(code)  

Global variables are considered 'to be avoided'. The coffeescript page that you linked to does have an alternative though:

If you'd like to create top-level variables for other scripts to use, attach them as properties on window, or on the exports object in CommonJS. The existential operator (covered below), gives you a reliable way to figure out where to add them; if you're targeting both CommonJS and the browser: exports ? this