Node.js Asynchronous File I / O

I am new to Node.js and recently learned about the module fs. I am a little confused regarding asynchronous and synchronous file I / O.

Consider the following test:

var fs = require('fs');

var txtfile = 'async.txt';
var buffer1 = Buffer(1024);
var buffer2 = '1234567890';

fs.appendFile(txtfile, buffer1, function(err) {
    if (err) { throw err };
    console.log('appended buffer1');
});

fs.appendFile(txtfile, buffer2, function(err) {
    if (err) { throw err };
    console.log('appended buffer2');
});

In about half the time when I run this, it prints appended buffer2to appended buffer1. But when I open a text file, the data is always displayed in the correct order - a bunch of garbage from Buffer(1024)followed 1234567890. I would expect a backward or messy mess.

What's going on here? Am I doing something wrong? Is there some kind of lower level I / O queue that maintains order?

I saw some talk about I / O differences in the file system with Node; I am on a Mac, if that matters.

+4
1

, , - SAME . , - .

. , - . , , , , , , , .. , , , . , ( ), . , console.log().

+5

Source: https://habr.com/ru/post/1538992/


All Articles