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?
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 = {};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With