Assign file contents to the target object
const assignFile = require('assign-file');
// foo/bar/baz.txt (Hello!)
assignFile({foo: {bar: 123}}, 'foo/bar/baz.txt', 'utf8', (err, res) => {
if (err) {
throw err;
}
res;
/* =>
{
foo: {
bar: {
baz: 'Hello!'
}
}
}; //=> true
*/
});
npm install assign-file
const assignFile = require('assign-file');
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.
const {deepEqual} = require('assert');
const assignFile = require('assign-file');
const target = {
fixtures: {
foo: 'bar'
}
};
assignFile(target, 'fixtures/images/00.jpg', (err, res) => {
if (err) {
throw err;
}
// Adds fixtures.images['00'] property to the target object.
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()
.
Copyright (c) 2014 - 2018 Shinnosuke Watanabe
Licensed under the MIT License.