Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Why do I keep getting the ReferenceError in node.js

Why do I keep getting the ReferenceError in node.js

Problem

I'm going the the Smashing Node.JS book and I keep getting a Reference Error when doing the file-explorer example. Why is this occurring and how can I correct the problem. I've follow the example in the book so I'm a little lost as to what's happening

    /**
* Module dependencies. 
*/ 

    var fs = require('fs')
        , stdin = process.stdin
        , stdout = process.stdout;

    fs.readdir(process.cwd(), function (err, files) {
      console.log('');

     if (!files.length) {
      return console.log('  \033[31m No files to show!\033[39m\n'); 
     } 

      console.log(' Select which file or directory you want to see\n');

      function file(i) {
    var filename = files[i]; 

    fs.stat(__dirname + '/' + filename, function (err, stat) {
      if (stat.isDirectory()) {
        console.log('   '+i+'   \033[36m' + filename + '/\033[39m'); 
      } else {
        console.log('       '+i+'   \033[90m' + filename + '\033[39m')
      }

      if (++i == files.length) {
        read();
      } else{
        file(i); 
      }
    });
  }

  file(0); 
});

function read() {
    console.log(''); 
    stdout.write('  \033[33mEnter your choice: \033[39m');

    stdin.resume(); 
    stdout.setEncoding('utf8'); 

    stdin.on('data', option); 

    function option( data ) {
        if (typeof files[Number(data)] !== "undefined" ) {
            stdout.write('  \033[31mEnter your choice: \033[39m');
        } else {
            stdin.pause(); 
        }
    }

}
Problem courtesy of: magreen03

Solution

At the moment read() is called, it does not have access to files, thus the reference-error when using typeof files[...].

An idea might be to move the }); after file(0) to the bottom of the file, thus having read in the fs.readdir(process.cwd(), function (err, files) { block which defines files.

However, I really hope this example will be expanded upon in your book: right now, it's not going to output the directory content of the dir you've selected, but will prompt you to enter a number over and over again.

Solution courtesy of: mabako

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Why do I keep getting the ReferenceError in node.js

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×