1

How do I export a variable (like 'data' below), so I can use the function below as a module:

//fooreader.js
var fs = require("fs");
var fileName = "foo.txt";

fs.exists(fileName, function(exists) {
  if (exists) {
    fs.stat(fileName, function(error, stats) {
      fs.open(fileName, "r", function(error, fd) {
        var buffer = new Buffer(stats.size);
        fs.read(fd, buffer, 0, buffer.length, null, function(error, bytesRead, buffer) {
          var data = buffer.toString("utf8", 0, buffer.length);
          console.log(data);
          fs.close(fd);
        });});});}});

I'd like to use it like a module:

//consumer.js
var fooreader = require('fooreader.js');
console.log(fooreader());

I understand that might be a little naive given the asynchronous read, so I tried putting 'fooreader' into a function that accepts a callback:

//fooreader.js
var fs = require("fs");
var fileName = "foo.txt";

var fooreader = function(callback){
fs.exists(fileName, function(exists) {
  if (exists) {
    fs.stat(fileName, function(error, stats) {
      fs.open(fileName, "r", function(error, fd) {
        var buffer = new Buffer(stats.size);
        fs.read(fd, buffer, 0, buffer.length, null, function(error, bytesRead, buffer) {
          var data = buffer.toString("utf8", 0, buffer.length);
          console.log(data);
          fs.close(fd);
          callback(data);
        });});});}});};
module.exports = fooreader;

and tried:

//consumer.js
var fooreader = require('fooreader.js');
fooreader(callback);
var callback = function(data){    
  console.log(data);
}

and got "TypeError: undefined is not a function". How do I make the callback work?

Antonius Bloch
  • 2,311
  • 2
  • 14
  • 14
  • so `callback` isn't being hoisted, because you are using variable assignment rather than function declaration syntax. If you said `function callback(data) { console.log(data) }` instaed, it would work. – Maus Jan 14 '14 at 06:29

2 Answers2

0

Define the callback before calling it in your last snippet. Everything else looks like it should work.

You have:

var fooreader = require('fooreader.js');
fooreader(callback);
var callback = function(data){    
  console.log(data);
}

When you run fooreader(callback), it's before callback has been defined. Switch the order of the commands and everything should work.

Scimonster
  • 32,893
  • 9
  • 77
  • 89
0

It works if I use an anonymous function to handle the callback. Makes sense as it's passing the function back to the module ...

//consumer.js
var fooreader = require('fooreader.js');
fooreader(function (data){    
  console.log(data);
});
Antonius Bloch
  • 2,311
  • 2
  • 14
  • 14