1.0.0 • Published 11 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-fileAPI
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.txtsetsfooproperty.foo/bar.txtsetsfoo.barproperty.foo/bar/baz.qux.txtsetsfoo.bar['baz.qux']property.../foo/bar.txtsets['..'].foo.barproperty.foo/../bar/baz.txtsetsbar.bazproperty.
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.