Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problems with use fs.stat in nodejs

Tags:

node.js

I trying make read file parameters. When I make this code:

  var fs = require('fs'),
    size = new Object();
fs.stat(file, function(err,stats){
         if(!err){
            size=stats;
         }
      })
   console.log(size);

It`s ok, when i trying use function:

 var fs = require('fs'),
    size = new Object();
function writeinfile(file){
   fs.stat(file, function(err,stats){
         if(!err){
            size=stats;
         }
      })
   console.log(size.size);  
}
writeinfile('error.log');

It`s not work. Could you help me that variant 2 work?

like image 569
IIEIIEJI Avatar asked Oct 29 '12 19:10

IIEIIEJI


1 Answers

Your console.log is outside your fs.stat callback. Fixed it:

 var fs = require('fs'),
    size = new Object();
function writeinfile(file){
   fs.stat(file, function(err,stats){
         if(!err){
            size=stats;
            console.log(size.size);  
         }
      })

}
writeinfile('error.log');

I've also rewritten your code to use more idiomatic (more common) syntax in Node.js:

var fs = require('fs');

function writeinfile (file, cb) {
  fs.stat(file, function(err,stats){
    if(err) return cb(err);
    cb(null, stats.size); 
  })
}

writeinfile('error.log', function(err, size) {
  if(err) {
    console.log(err);
    return;
  }
  console.log('The size of the file is ' + size);
});

As Herman mentioned in his answer, it would be a good idea to choose a better function name if you are not writing to a file.

Last thing, in Javascript, you can use {} as a shortcut for new Object(). For example: var size = {};

like image 92
Olivier Lalonde Avatar answered Oct 22 '22 08:10

Olivier Lalonde