Skip to content

Assign file contents to the target object

License

Notifications You must be signed in to change notification settings

shinnn/assign-file

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

5 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

assign-file

npm version Build Status Coverage Status

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
  */
});

Installation

Use npm.

npm install assign-file

API

const 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 sets foo property.
  • foo/bar.txt sets foo.bar property.
  • foo/bar/baz.qux.txt sets foo.bar['baz.qux'] property.
  • ../foo/bar.txt sets ['..'].foo.bar property.
  • foo/../bar/baz.txt sets bar.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().

License

Copyright (c) 2014 - 2018 Shinnosuke Watanabe

Licensed under the MIT License.

About

Assign file contents to the target object

Resources

License

Stars

Watchers

Forks

Packages

No packages published