ariestav
ariestav

Reputation: 2967

Why is this readFile operation in Node throwing an error?

I have this code using socket.io on a Node server:

io.sockets.on(
   'connection'
   ,function (socket) {
    reader = require('fs');
    fileContents = reader.readFile(__dirname + '/textCharacters.txt'
                                   ,'utf8'
                                   ,function(data, err) {
                                              if (err) throw err;
                                              console.log(data);
                                    }
                           );
    socket.emit('retrievedFileContent', {content:fileContents} );
    }
);

When I check the Node server debug, the error shows the contents of the file, so I know the file is being read, but why isn't it being returned to the fileContents variable?

Upvotes: 1

Views: 835

Answers (1)

maerics
maerics

Reputation: 156662

Because the readFile(filename, encoding, callback) function doesn't return the file contents, it passes them as the second argument to the given callback function. Try modifying your code as such:

var fs = require('fs');

io.sockets.on('connection', function (socket) {
  var filename = __dirname + '/textCharacters.txt';
  fs.readFile(filename, 'utf8', function(err, data) {
    if (err) throw err;
    socket.emit('retrievedFileContent', {content:data});
  });
});

Upvotes: 3

Related Questions