开发者

what happens when I read/write the same file?

开发者 https://www.devze.com 2023-04-07 09:52 出处:网络
I\'m learning about NodeJS\'s event model. I\'m confused about the output. the code simply write some text to a file and read it back.

I'm learning about NodeJS's event model.

I'm confused about the output.

the code simply write some text to a file and read it back. the execution order seems out of my control.

var fs = require('fs');  
var ws = fs.createWriteStream("my_file.txt");  
ws.once('open', function(fd) {  
  console.log( 'ws_open' );  
  ws.write("My first row\n");  
  ws.write("My second row\n");  
  ws.write("My third row\n");  
  ws.destroySoon();  
});  

ws.once('close', function() {  
  console.log( 'ws_close');  
});  

var rs = fs.createReadStream("my_file.txt");  
rs.setEncoding('utf8');  
rs.once('open', function(fd) {  
  console.log( 'rs_open' );  
});  
rs.once('close', function() {  
  console.log( 'rs_close');  
});  

rs.onc开发者_高级运维e('data', function(data) {  
  console.log( 'rs_data' );  
  console.log( data );  
});  

rs.once('error', function(exception) {  
  console.log( 'rs_exception' );  
  console.log( exception );  
});  

Here is the output.

rs_open

ws_open

rs_close

ws_close

Sometimes, it becomes

ws_open

rs_open

rs_data

My first row

rs_close

ws_close

Can anyone give me some explanation?

Thank in advance.


You are doing asynchronous stuff as if it is synchronous. Just because something is lower in the code doesn't mean it happens later. If you don't want to read the file until you are done writing it, put your read inside the callback for the write.

as in : (simplified)

writeFile (name, writeData, function (error) {
  if (error)
    .... // handle error
  else { // successfully wrote file
   readFile(name, function (error, readData) {
     if (error) 
        .... // handle error
     else { // successfully read file
       ... // do something with readData
     }
    });
  }
 }); 
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号