当我读/写相同的文件时会发生什么?

我正在学习NodeJS的事件模型。

我对输出感到困惑。

代码只需将一些文本写入文件并将其读回。 执行顺序似乎不受我的控制。

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.once('data', function(data) { console.log( 'rs_data' ); console.log( data ); }); rs.once('error', function(exception) { console.log( 'rs_exception' ); console.log( exception ); }); 

这是输出。

rs_open
ws_open
rs_close
ws_close

有时候,它变成了

ws_open
rs_open
rs_data
我的第一排

rs_close
ws_close

任何人都可以给我一些解释?

预先感谢。

你正在做asynchronous的东西,就好像它是同步的。 只是因为代码中较低的东西并不意味着它会在稍后发生。 如果在写完文件之前不想读取文件,请将读取内容写入callback函数中。

如:(简体)

 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 } }); } });