首页 \ 问答 \ Node.js异步文件I / O.(Node.js Asynchronous File I/O)

Node.js异步文件I / O.(Node.js Asynchronous File I/O)

我是Node.js的新手,最近了解了fs模块。 我对异步与同步文件i / o有点困惑。

考虑以下测试:

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

大约一半的时间我运行它,它appended buffer2appended buffer1之前打印appended buffer1 。 但是当我打开文本文件时,数据总是看起来是正确的顺序 - 来自Buffer(1024)的一堆垃圾后跟1234567890 。 我原本期望反向或乱七八糟的混乱。

这里发生了什么? 难道我做错了什么? 是否有某种维持秩序的低级i / o队列?

我已经看到一些关于文件系统与Node的i / o差异的讨论; 我在Mac上,如果这有任何区别。


I'm new to Node.js and recently learned about the fs module. I'm a little confused about asynchronous vs. 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');
});

About half the time when I run this, it prints appended buffer2 before appended buffer1. But when I open the text file, the data always appears to be in the right order - a bunch of garbage from Buffer(1024) followed by 1234567890. I would have expected the reverse or a jumbled 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've seen some talk about filesystem i/o differences with Node; I'm on a Mac if that makes any difference.


原文:https://stackoverflow.com/questions/23427430
更新时间:2023-11-12 09:11

最满意答案

fFoo类的一个实例,它继承自ActiveRecord::Base ,它不是Hash实例。

要通过它的值(使用key )获取属性的名称,首先必须得到fActiveRecord :: AttributeMethods# attributes的哈希值:

f.attributes.key('dave') # `attributes` method returns a Hash instance
#=> "name"

有什么不同

总结:对象类中定义的实例方法的差异。


f is an instance of Foo class, which inherits from ActiveRecord::Base, it is not a Hash instance.

To get the attribute's name by it's value (using key), you have to get a hash of f's ActiveRecord::AttributeMethods#attributes first:

f.attributes.key('dave') # `attributes` method returns a Hash instance
#=> "name"

What is the difference

To sum up: the difference in the instance methods defined in the object's class.

相关问答

更多
  • 只有它们存在时它才会获得所有的src值。 否则它会跳过那个