节点流,将数组包装为对象

时间:2014-07-11 13:15:17

标签: json node.js stream

我的表单中有一个metadata对象

{ 
    filename: "hugearray.json",
    author: "amenadiel",
    date: "2014-07-11",
    introduction: "A huge ass array I want to send to the browser"
}

那个hugearray.json是我文件夹中的一个文本文件,顾名思义,它包含一个潜在无限元素的数组。

[
    [14, 17, 25, 38, 49],
    [14, 41, 54, 57, 58],
    [29, 33, 39, 53, 59],
    ...
    [03, 14, 18, 34, 37],
    [03, 07, 14, 29, 33],
    [05, 16, 19, 30, 49]
]

我想要实现的是向浏览器输出一个原始对象的对象,其中包含额外的“内容”键,即巨大的数组

{ 
    filename: "hugearray.json",
    author: "amenadiel",
    date: "2014-07-11",
    introduction: "A huge ass array I want to send to the browser",
    content: [
                [14, 17, 25, 38, 49],
                ...
                [05, 16, 19, 30, 49]
             ]
}

但由于我不知道数组大小,我不想在输出之前将整个内容存储在内存中,所以我想到了使用流。我可以使用

精确地传输数组
var readStream = fs.createReadStream("hugearray.json");

readStream.on('open', function () {
    readStream.pipe(res);
});

当然,我可以使用

将元数据对象发送到res
res.json(metadata);

我尝试解构元数据,编写每个key : value对并打开内容密钥,然后管理文件结果,然后关闭花括号。它似乎不起作用:

{ 
    filename: "hugearray.json",
    author: "amenadiel",
    date: "2014-07-11",
    introduction: "A huge ass array I want to send to the browser",
    content:
}[
    [14, 17, 25, 38, 49],
    [14, 41, 54, 57, 58],
    [29, 33, 39, 53, 59],
    ...
    [03, 14, 18, 34, 37],
    [03, 07, 14, 29, 33],
    [05, 16, 19, 30, 49]
]

我想我需要将流包装在我的元数据内容密钥中,而不是尝试输出json并流式传输到结果中。 ¿有什么想法吗?

1 个答案:

答案 0 :(得分:0)

好吧,我的问题没有引起注意,但让我赢得了Tumbleweed徽章。这是件事。

我一直在调查,我提出了一个解决方案。我希望找到一个单行,但这个也工作,到目前为止,我已经能够输出几个MB到浏览器,而我的节点过程中没有明显的性能损失。

这是我使用的方法

app.get('/node/arraystream', function (req, res) {
    var readStream = fs.createReadStream("../../temp/bigarray.json");
    var myObject = {
        filename: "hugearray.json",
        author: "amenadiel",
        date: "2014-07-11",
        introduction: "A huge ass array I want to send to the browser"
    };

    readStream.on('open', function () {
        console.log('readStream open');
        var myObjectstr = JSON.stringify(myObject);
        res.write(myObjectstr.substring(0, myObjectstr.length - 1) + ',"content":');
    });

    readStream.on('error', function (err) {
        console.log('readStream error', err);
        throw err;
    });

    readStream.on('close', function () {
        console.log('readStream closed');
        readStream.destroy();
        res.write('}');
        res.end();

    });

    readStream.on('data', function (data) {
        console.log('readStream received data', data.length);
        var buf = new Buffer(data, 'ascii');
        res.write(buf);
    });

});

基本上,我不是将对象变成流,而是将数组转换为缓冲区。