You need to put the console.log(size.size); inside the callback function, but i think i need explain better.
You need to learn about asynchronous calls and the Node.js Event Loop. Node.js was created to paralelize resources in a better way that creating threads for problems that are more IO Intensive (like web servers) than CPU Intensive. The idea is that a single thread for the logic with non-blocking calls to use IO is better than create multiple threads and call blocks function to use IO.
If you program in another language, you should be familiar with the sinchronous version of your algorithm:
var fs = require('fs'),
size = new Object();
function writeinfile(file) {
var stats = fs.statSync(path);
size = stats.size;
console.log(size);
};
writeinfile('error.log');
This is Node.js code, but this isn't the Node way. When you call statSync(), your script block to wait for read the stats from the disk.
BUT, when you use just fs.stat(), your program will run until the end of code, WHILE the disk is reading. All the next lines will be run before the program achieve the Event Loop. Just when the stat be ready and the program run until the end, the event loop will call the callback function that you pass by argument in fs.stat(callback) call.
So, in your code, you call a stat (assynchronous version), and try use a value that isn't ready yet, because the code after the assynchronous calls always will be run before callback be called.
The first version I think work just because you should be typping the code manually in the interpreter, so, the time you need to type the next line is enought to the program achieve the event loop. In this mode, each time that you type a command, press enter and that code is run, that is, you get a return, the events in event loop will be called after.