Skip to content

Instantly share code, notes, and snippets.

@rvagg
Last active December 16, 2015 19:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save rvagg/f35c8fb674621d428fb0 to your computer and use it in GitHub Desktop.
Save rvagg/f35c8fb674621d428fb0 to your computer and use it in GitHub Desktop.
config -> object mapping keys to stat & uri
{
"foo": "/path/to/foo"
, "bar": "/path/to/bar"
}
const fs = require('fs')
, path = require('path')
, execute = require('execute')
function transform (fn) {
return function transformer (value, callback) {
if (typeof fn == 'function')
return fn(value, callback)
callback(null, fn)
}
}
function pluckConfigProperty (config) {
return transform(function (prop, callback) {
if (typeof config[prop] != 'string')
return callback('Required configuration property not set: ' + prop)
return callback(null, config[prop])
})
}
function toUri (root) {
return transform(function (p, callback) {
callback(null, path.resolve(root, p))
})
}
function toStatAndUri () {
return transform(function (uri, callback) {
fs.stat(uri, function (err, stat) {
if (err)
return callback(err)
return callback(null, { uri: uri, stat: stat })
})
})
}
function eachTransform () {
var transforms = Array.prototype.slice.call(arguments)
return function (value, callback) {
var i = 0
, execute = function () {
if (i == transforms.length)
return callback(null, value)
transforms[i++](value, function (err, _value) {
if (err)
return callback(err)
value = _value
execute()
})
}
execute()
}
}
function configToStat (root, config, properties, callback) {
var transforms = eachTransform(
pluckConfigProperty(config)
, toUri(root)
, toStatAndUri()
)
execute(
properties.reduce(function (p, k) {
p[k] = transforms.bind(null, k)
return p
}, {})
, callback
)
}
function loadFiles (root, config) {
configToStat(root, config, [ 'foo', 'bar' ], function (err, result) {
if (err)
return console.error('Error:', err)
console.log(result)
})
}
// expected result:
{ foo:
{ stat:
{ dev: 2065,
mode: 16893,
nlink: 2,
uid: 1000,
gid: 1000,
rdev: 0,
blksize: 4096,
ino: 11701430,
size: 4096,
blocks: 8,
atime: Tue Apr 30 2013 14:49:26 GMT+1000 (EST),
mtime: Tue Apr 30 2013 14:49:26 GMT+1000 (EST),
ctime: Tue Apr 30 2013 14:49:26 GMT+1000 (EST) },
uri: '/path/to/foo' },
bar:
{ stat:
{ dev: 2065,
mode: 16893,
nlink: 2,
uid: 1000,
gid: 1000,
rdev: 0,
blksize: 4096,
ino: 11817511,
size: 4096,
blocks: 8,
atime: Tue Apr 30 2013 14:49:33 GMT+1000 (EST),
mtime: Tue Apr 30 2013 14:49:33 GMT+1000 (EST),
ctime: Tue Apr 30 2013 14:49:33 GMT+1000 (EST) },
uri: '/path/to/bar' } }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment