I am learning nodejs. I am having some hard time understanding how asynchronous functions works. My question is related to the code below. I am trying to do the following things in the following exact same order:
- Open the file a.txt.
- Read it.
- Print its content.
- Close it and log that the file has been closed.
- Open it again.
- Overwrite it with new content.
The problem is that as per the output I am getting, it seems that I am not controlling the sequence of these event. This is the output I am getting in the console:
just read 21 bytes / this is my test files / just wrote 30 bytes /file close and ready for write
So, as you can see, for some reason the program is writing in the file before it log that the file was closed. I was trying to close it, log that it was closed and then to write in the file.
So I think I have a problem controlling the flow of events. Can you point out what am I doing wrong?
This the the code:
var fs = require('fs');
//What I am trying to do here is: open a file a.txt, read it, print its content and then //close the file and log that it has been closed.
//Then, open it again and overwrite it.
fs.open('a.txt', 'r', function(err, fd){
if(err){throw err;}
var readBuffer = new Buffer(1024);
var bufferOffset = 0;
var filePosition = 0;
var readBufferLength = readBuffer.length;
fs.read(fd, readBuffer, bufferOffset, readBufferLength, filePosition, function(err, readBytes){
if(err){throw err;}
console.log('just read ' + readBytes + ' bytes');
console.log(readBuffer.slice(0,readBytes).toString());
fs.close(fd,function(){
console.log('file close and ready for write');
});
});
});
fs.open('a.txt', 'r+', function(err,fd){
if(err){throw err;}
var writeBuffer = new Buffer('saul lugo overwrote this file!');
var bufferOffset = 0;
var writeBufferLength = writeBuffer.length;
var filePosition = null;
fs.write(fd, writeBuffer, bufferOffset, writeBufferLength, filePosition, function(err, writeBytes){
if(err){throw err;}
if(writeBytes>0){
console.log('just wrote ' + writeBytes + ' bytes.');
}
});
});