Node.js - 我可以在Redis中将可写流存储为JSON吗?

时间:2011-12-15 23:36:34

标签: json node.js stream redis

我仍在努力完全理解node.js中的流。如果我创建一个可写流,我是否能够将流对象作为JSON存储在Redis中,然后再访问它,并继续写入它(在JSON.parse之后)?

示例:

var fs = require( 'fs' );
var redis = require( 'redis' );

var streamName = fs.createWriteStream(upfilePath, streamopts);
streamName = JSON.stringify(streamName);

rclient.set('streamJSON', streamName);

.... 

var myNewdata = 'whatever';
rclient.get('streamJSON', function (err, streamJSON) {
   var recoveredStream = JSON.parse(streamJSON);

   recoveredStream.write(myNewdata, function (err, written, buffer) {
      //write successful??
   }
}

1 个答案:

答案 0 :(得分:3)

您无法在redis上存储变量引用。您只需要存储文件名,然后使用a标志重新打开流,该标志允许您向其追加数据。

我认为这是一个非常有趣的问题,并创建了这个,允许您保存流的状态,然后再使用它。但是,如果您只使用a标志,我就不明白这一点。可能对ReadableStreams很有用。

var fs = require('fs');

exports.stringify = function(stream) {
  var obj = {
      path: stream.path
    , writable: stream.writable
    , fd: stream.fd
    , options: {
        encoding: stream.encoding
      , mode: stream.mode
    }
  };

  if (stream.writable) {
    obj.bytesWritten = stream.bytesWritten;

  } else {
    obj.options.bufferSize = stream.bufferSize;
    obj.bytesRead = stream.bytesRead;
  }

  return JSON.stringify(obj);
};

exports.parse = function(json, callback) {
  var obj = JSON.parse(json);
  var stream;

  if (obj.writable) {
    obj.options.flags = 'a';
    stream = fs.createWriteStream(obj.path, obj.options);
    stream.bytesWritten = obj.bytesWritten;


  } else {
    stream = fs.createReadStream(obj.path, obj.options);
    stream.bytesRead = obj.bytesRead;
  }

  // if stream was already opened, wait until it is
  if (obj.fd !== null) {
    stream.on('open', function() {
      callback(null, stream);
    });
  } else {
    process.nextTick(function() {
      callback(null, stream);
    });
  }

  return stream;
};