From cf7e5884cd3908f2200fac3684ebebdb5cbeb577 Mon Sep 17 00:00:00 2001 From: Samy Pesse Date: Fri, 6 May 2016 10:53:55 +0200 Subject: [PATCH] Add method readAsStream on fs model --- lib/fs/node.js | 3 ++- lib/models/fs.js | 29 ++++++++++++++++++++++++++++- lib/utils/fs.js | 1 + 3 files changed, 31 insertions(+), 2 deletions(-) diff --git a/lib/fs/node.js b/lib/fs/node.js index 9b8c05657..dfe9fae90 100644 --- a/lib/fs/node.js +++ b/lib/fs/node.js @@ -36,6 +36,7 @@ module.exports = function createNodeFS(root) { fsReadFile: fs.readFile, fsStatFile: fs.stat, fsReadDir: fsReadDir, - fsLoadObject: fsLoadObject + fsLoadObject: fsLoadObject, + fsReadAsStream: fs.readStream }); }; diff --git a/lib/models/fs.js b/lib/models/fs.js index ab65dd5bb..12aee537e 100644 --- a/lib/models/fs.js +++ b/lib/models/fs.js @@ -1,5 +1,6 @@ var path = require('path'); var Immutable = require('immutable'); +var stream = require('stream'); var File = require('./file'); var Promise = require('../utils/promise'); @@ -13,7 +14,9 @@ var FS = Immutable.Record({ fsReadFile: Function(), fsStatFile: Function(), fsReadDir: Function(), - fsLoadObject: null + + fsLoadObject: null, + fsReadAsStream: null }); /** @@ -111,6 +114,30 @@ FS.prototype.readAsString = function(filename, encoding) { }); }; +/** + Read file as a stream + + @param {String} filename + @return {Promise} +*/ +FS.prototype.readAsStream = function(filename) { + var that = this; + var filepath = that.resolve(filename); + var fsReadAsStream = this.get('fsReadAsStream'); + + if (fsReadAsStream) { + return Promise(fsReadAsStream(filepath)); + } + + return this.read(filename) + .then(function(buf) { + var bufferStream = new stream.PassThrough(); + bufferStream.end(buf); + + return bufferStream; + }); +}; + /** Read stat infos about a file diff --git a/lib/utils/fs.js b/lib/utils/fs.js index da22fdb33..35839a329 100644 --- a/lib/utils/fs.js +++ b/lib/utils/fs.js @@ -157,6 +157,7 @@ module.exports = { statSync: fs.statSync, readdir: Promise.nfbind(fs.readdir), writeStream: writeStream, + readStream: fs.createReadStream, copy: Promise.nfbind(cp), copyDir: Promise.nfbind(cpr), tmpFile: genTmpFile,