Skip to content

Commit

Permalink
Adds memory file system support (including tests) Closes pillarjs#160
Browse files Browse the repository at this point in the history
* Enables configuration to specify which file system to use to send files by default.
  Default: standard node js fs module (require('fs'))
* Provides basic tests via global injection
  • Loading branch information
hinell committed Feb 13, 2019
1 parent acefad9 commit dad855e
Show file tree
Hide file tree
Showing 5 changed files with 2,384 additions and 114 deletions.
22 changes: 18 additions & 4 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,10 @@ function send (req, path, options) {
return new SendStream(req, path, options)
}

var errors = {}
errors.INVALID_OPTION_FS_STAT = new TypeError('Invalid option: Incompatible file system interface: fs.stat() method is expected')
errors.INVALID_OPTION_FS_CRTSTRM = new TypeError('Invalid option: Incompatible file system interface: fs.createReadStream() method is expected')
send.errors = errors
/**
* Initialize a `SendStream` with the given `path`.
*
Expand All @@ -101,6 +105,16 @@ function SendStream (req, path, options) {
this.options = opts
this.path = path
this.req = req
this.fs = opts.fs || fs

// Checking if provided "fs" is compatible
if (!typeof this.fs.stat === `function`) {
throw errors.INVALID_OPTION_FS_STAT
}

if (!typeof this.fs.createReadStream === `function`) {
throw errors.INVALID_OPTION_FS_CRTSTRM
}

this._acceptRanges = opts.acceptRanges !== undefined
? Boolean(opts.acceptRanges)
Expand Down Expand Up @@ -718,7 +732,7 @@ SendStream.prototype.sendFile = function sendFile (path) {
var self = this

debug('stat "%s"', path)
fs.stat(path, function onstat (err, stat) {
this.fs.stat(path, function onstat (err, stat) {
if (err && err.code === 'ENOENT' && !extname(path) && path[path.length - 1] !== sep) {
// not found, check extensions
return next(err)
Expand All @@ -739,7 +753,7 @@ SendStream.prototype.sendFile = function sendFile (path) {
var p = path + '.' + self._extensions[i++]

debug('stat "%s"', p)
fs.stat(p, function (err, stat) {
self.fs.stat(p, function (err, stat) {
if (err) return next(err)
if (stat.isDirectory()) return next()
self.emit('file', p, stat)
Expand Down Expand Up @@ -767,7 +781,7 @@ SendStream.prototype.sendIndex = function sendIndex (path) {
var p = join(path, self._index[i])

debug('stat "%s"', p)
fs.stat(p, function (err, stat) {
self.fs.stat(p, function (err, stat) {
if (err) return next(err)
if (stat.isDirectory()) return next()
self.emit('file', p, stat)
Expand All @@ -793,7 +807,7 @@ SendStream.prototype.stream = function stream (path, options) {
var res = this.res

// pipe
var stream = fs.createReadStream(path, options)
var stream = this.fs.createReadStream(path, options)
this.emit('stream', stream)
stream.pipe(res)

Expand Down

0 comments on commit dad855e

Please sign in to comment.