1.0.0 • Published 9 years ago
assign-file v1.0.0
assign-file
Assign file contents to the target object
var assignFile = require('assign-file');
// foo/bar/baz.txt (Hello!)
assignFile({foo: {bar: 123}}, 'foo/bar/baz.txt', 'utf8', function(err, res) {
if (err) {
throw err;
}
res;
/* =>
{
foo: {
bar: {
baz: 'Hello!'
}
}
}; //=> true
*/
});
Installation
npm install assign-file
API
var assignFile = require('assign-file');
assignFile(target, filePath , options, callback)
target: object
filePath: String
(a relative file path)
options: Object
or String
(file encoding)
callback: Function
It asynchronously reads a file, then assigns the file contents to the target object as a property.
The names of the assigned properties are based on the file path. For example,
foo.txt
setsfoo
property.foo/bar.txt
setsfoo.bar
property.foo/bar/baz.qux.txt
setsfoo.bar['baz.qux']
property.../foo/bar.txt
sets['..'].foo.bar
property.foo/../bar/baz.txt
setsbar.baz
property.
var assert = require('assert');
var assignFile = require('assign-file');
var target = {
fixtures: {
foo: 'bar'
}
};
assignFile(target, 'fixtures/images/00.jpg', function(err, res) {
if (err) {
throw err;
}
// Adds fixtures.images['00'] property to the target object.
assert.deepEqual(res, {
fixtures: { // overrides fixtures.foo property
images: {
'00': <Buffer ... > // new property
}
}
});
});
All options and callback function can be used in the same way as set-property-from-file. The only difference from set-property-from-file is that assign-file always overwrites existing ones using Object.assign()
.
License
Copyright (c) 2014 Shinnosuke Watanabe
Licensed under the MIT License.