4.0.4 • Published 1 year ago

folder-hash v4.0.4

Weekly downloads
79,736
License
MIT
Repository
github
Last release
1 year ago

Create a hash checksum over a folder or a file.
The hashes are propagated upwards, the hash that is returned for a folder is generated over all the hashes of its children.
The hashes are generated with the sha1 algorithm and returned in base64 encoding by default.

Each file returns a name and a hash, and each folder returns additionally an array of children (file or folder elements).

Usage

First, install folder-hash with npm install --save folder-hash or yarn add folder-hash.

Simple example

To see differences to the last version of this package, I would create hashes over all .js and .json files. But ignore everything inside folders starting with a dot, and also from the folders node_modules, test_coverage. The structure of the options object is documented below.
This example is also stored in ./examples/readme-example1.js.

const { hashElement } = require('folder-hash');

const options = {
  folders: { exclude: ['.*', 'node_modules', 'test_coverage'] },
  files: { include: ['*.js', '*.json'] },
};

console.log('Creating a hash over the current folder:');
hashElement('.', options)
  .then(hash => {
    console.log(hash.toString());
  })
  .catch(error => {
    return console.error('hashing failed:', error);
  });

The returned information looks for example like this:

Creating a hash over the current folder:
{ name: '.', hash: 'YZOrKDx9LCLd8X39PoFTflXGpRU=,'
  children: [
    { name: 'examples', hash: 'aG8wg8np5SGddTnw1ex74PC9EnM=,'
      children: [
        { name: 'readme-example1.js', hash: 'Xlw8S2iomJWbxOJmmDBnKcauyQ8=' }
        { name: 'readme-with-callbacks.js', hash: 'ybvTHLCQBvWHeKZtGYZK7+6VPUw=' }
        { name: 'readme-with-promises.js', hash: '43i9tE0kSFyJYd9J2O0nkKC+tmI=' }
        { name: 'sample.js', hash: 'PRTD9nsZw3l73O/w5B2FH2qniFk=' }
      ]}
    { name: 'index.js', hash: 'kQQWXdgKuGfBf7ND3rxjThTLVNA=' }
    { name: 'package.json', hash: 'w7F0S11l6VefDknvmIy8jmKx+Ng=' }
    { name: 'test', hash: 'H5x0JDoV7dEGxI65e8IsencDZ1A=,'
      children: [
        { name: 'parameters.js', hash: '3gCEobqzHGzQiHmCDe5yX8weq7M=' }
        { name: 'test.js', hash: 'kg7p8lbaVf1CPtWLAIvkHkdu1oo=' }
      ]}
  ]}

And the structure may be traversed to e.g. create incremental backups.

It is also possible to only match the full path and not the basename. The same configuration could look like this:
You should be aware that *nix and Windows behave differently, so please use caution.

const options = {
  folders: {
    exclude: ['.*', '**.*', '**node_modules', '**test_coverage'],
    matchBasename: false,
    matchPath: true,
  },
  files: {
    //include: ['**.js', '**.json' ], // Windows
    include: ['*.js', '**/*.js', '*.json', '**/*.json'], // *nix
    matchBasename: false,
    matchPath: true,
  },
};

Parameters for the hashElement function

Options

Default values

{
    algo: 'sha1',       // see crypto.getHashes() for options in your node.js REPL
    encoding: 'base64', // 'base64', 'base64url', 'hex' or 'binary'
    files: {
        exclude: [],
        include: [],
        matchBasename: true,
        matchPath: false,
        ignoreBasename: false,
        ignoreRootName: false
    },
    folders: {
        exclude: [],
        include: [],
        matchBasename: true,
        matchPath: false,
        ignoreRootName: false
    },
    symbolicLinks: {
        include: true,
        ignoreBasename: false,
        ignoreTargetPath: true,
        ignoreTargetContent: false,
        ignoreTargetContentAfterError: false,
    }
}

Rules object properties

Symlink options

Configure, how symbolic links should be hashed.
To understand how the options can be combined to create a specific behavior, look into test/symbolic-links.js.

Command line usage

After installing it globally via

$ npm install -g folder-hash

You can use it like this:

# local folder
$ folder-hash -c config.json .
# local folder
$ folder-hash
# global folder
$ folder-hash /user/bin

It also allows to pass an optional JSON configuration file with the -c or --config flag, which should contain the same configuration as when using the JavaScript API.

You can also use a local version of folder-hash like this:

$ npx folder-hash --help
Use folder-hash on cli like this:
  folder-hash [--config <json-file>] <file-or-folder>

Examples

Other examples using promises

See file ./examples/readme-with-promises.js

const path = require('path');
const { hashElement } = require('folder-hash');

// pass element name and folder path separately
hashElement('test', path.join(__dirname, '..'))
  .then(hash => {
    console.log('Result for folder "../test":', hash.toString(), '\n');
  })
  .catch(error => {
    return console.error('hashing failed:', error);
  });

// pass element path directly
hashElement(__dirname)
  .then(hash => {
    console.log(`Result for folder "${__dirname}":`);
    console.log(hash.toString(), '\n');
  })
  .catch(error => {
    return console.error('hashing failed:', error);
  });

// pass options (example: exclude dotFolders)
const options = { encoding: 'hex', folders: { exclude: ['.*'] } };
hashElement(__dirname, options)
  .then(hash => {
    console.log('Result for folder "' + __dirname + '" (with options):');
    console.log(hash.toString(), '\n');
  })
  .catch(error => {
    return console.error('hashing failed:', error);
  });

Other examples using error-first callbacks

See ./examples/readme-with-callbacks.js

const path = require('path');
const { hashElement } = require('folder-hash');

// pass element name and folder path separately
hashElement('test', path.join(__dirname, '..'), (error, hash) => {
  if (error) {
    return console.error('hashing failed:', error);
  } else {
    console.log('Result for folder "../test":', hash.toString(), '\n');
  }
});

// pass element path directly
hashElement(__dirname, (error, hash) => {
  if (error) {
    return console.error('hashing failed:', error);
  } else {
    console.log('Result for folder "' + __dirname + '":');
    console.log(hash.toString(), '\n');
  }
});

// pass options (example: exclude dotFiles)
const options = { algo: 'md5', files: { exclude: ['.*'], matchBasename: true } };
hashElement(__dirname, options, (error, hash) => {
  if (error) {
    return console.error('hashing failed:', error);
  } else {
    console.log('Result for folder "' + __dirname + '":');
    console.log(hash.toString());
  }
});

Behavior

The behavior is documented and verified in the unit tests. Execute npm test or mocha test, and have a look at the test subfolder.
You can also have a look at the CircleCI report. CircleCI

Creating hashes over files (with default options)

The hashes are the same if:

  • A file is checked again
  • Two files have the same name and content (but exist in different folders)

The hashes are different if:

  • A file was renamed or its content was changed
  • Two files have the same name but different content
  • Two files have the same content but different names

Creating hashes over folders (with default options)

Content means in this case a folder's children - both the files and the subfolders with their children.

The hashes are the same if:

  • A folder is checked again
  • Two folders have the same name and content (but have different parent folders)

The hashes are different if:

  • A file somewhere in the directory structure was renamed or its content was changed
  • Two folders have the same name but different content
  • Two folders have the same content but different names

License

MIT, see LICENSE.txt

@oscarltz/workspace-dev-runnercryptowerk-clikurigashvili-testpackagekurigashvili-testpackage-xftsckakuri-ask-clikakuri2-ask-cli@oscarltz/monorepo-build@blockware/blockctl-command-registry@everything-registry/sub-chunk-1688serverless-layersserverless-plugin-layersshenexpressshenfirsttestpackageerrmsgselm-reviewssdeployencrypt-payloadsdelightmom-resourcecreate-img-core-customcreate-static-build@dinii-inc/tamashiiroot-resolver-pluginsls-layerssls-layers-261ecu-servereitri-clidobieasy-web-app-builder@aws-amplify/amplify-category-functionopenblock-learningmlopenblock-resourceopenblock-resource-cli@aws-amplify/cli-internalopenapi3-to-typescriptbundlee@aws-amplify/cli-builder@aws-amplify/amplify-provider-awscloudformation@backpackjs/transformsbuild-from-entry@bdelab/roar-vocab@bdeco/nodeshcfs-pulumicfs-pulumi-awscfs-pulumi-expocleargclearg-cli@campbell/vueapps@sweetlikepete/brick@swsdk/connector@swtdk/connector@sw-tsdk/connector@communities-webruntime/servicescdk-build-tools@bdcash-protocol/bvc@bdcash-protocol/nodesh@coffee-shope/barista@devfied/flashrepo@driven-education/hub-cli@dreamlines.dev/amplify-cli@americanexpress/one-app-bundler@americanexpress/one-app-server-bundleraws-lambda.jsflash-repoflex-ts-sdksubrosatest-aztakomogatsby-plugin-cryptowerk-blockchain@epsyhealth/amplify-provider-awscloudformation-epsy@foxpage/foxpage-cli@flashcoffee/serverless-layers@flatpack/compiler@flink-app/flink@fstore/cli@fstore/shared@fastkit/node-util@fastkit/hashed-sync@pinf-it/core@project-furnace/stack-processor@ra-bootcamp/hub-cli@redspot/watcher@raisely/cli@samverschueren/amplify-cli@resoc/create-img-core@noovolari/leapp-cli@noovolari/leapp-cli-nightly@noovolari/leapp-core@noovolari/leapp-core-nightly@nutui/markdown-to-vueakid-resourceakid-resource-cli@spirit-fish/cli@webruntime/framework-server@webruntime/server@webis-de/scriptor@webiny/serverless-aws-s3-object@wessberg/fileloaderanswers-toolkit@xmorse/deployment-utils
4.0.4

1 year ago

4.0.3

1 year ago

4.0.2

2 years ago

4.0.1

3 years ago

4.0.0

4 years ago

3.3.3

4 years ago

3.3.2

4 years ago

3.3.1

4 years ago

3.3.0

5 years ago

3.2.0

5 years ago

3.1.0

5 years ago

3.0.0

5 years ago

2.1.3

5 years ago

2.1.2

5 years ago

2.1.1

6 years ago

2.1.0

6 years ago

2.0.0

6 years ago

1.1.2

7 years ago

1.1.1

7 years ago

1.1.0

7 years ago

1.0.5

7 years ago

1.0.4

8 years ago

1.0.3

8 years ago

1.0.2

8 years ago

1.0.0

8 years ago