Socket
Socket
Sign inDemoInstall

hasha

Package Overview
Dependencies
Maintainers
1
Versions
16
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

hasha - npm Package Compare versions

Comparing version 5.2.2 to 6.0.0

226

index.d.ts

@@ -1,167 +0,125 @@

/// <reference types="node"/>
import {LiteralUnion} from 'type-fest';
import {Hash} from 'crypto';
import {type Hash} from 'node:crypto';
import {type LiteralUnion} from 'type-fest';
declare namespace hasha {
type ToStringEncoding = 'hex' | 'base64' | 'latin1';
type HashaInput = Buffer | string | Array<Buffer | string>;
type HashaEncoding = ToStringEncoding | 'buffer';
export type HashInput = HashSyncInput | NodeJS.ReadableStream;
export type HashSyncInput = Uint8Array | string | Array<Uint8Array | string>;
export type StringEncoding = 'hex' | 'base64' | 'latin1';
export type HashEncoding = StringEncoding | 'buffer';
type AlgorithmName = LiteralUnion<
'md5' | 'sha1' | 'sha256' | 'sha512',
string
>;
export type HashAlgorithm = LiteralUnion<
'md5' | 'sha1' | 'sha256' | 'sha512',
string
>;
interface Options<EncodingType = HashaEncoding> {
/**
Encoding of the returned hash.
export type Options<EncodingType extends HashEncoding = 'hex'> = {
/**
The encoding of the returned hash.
@default 'hex'
*/
readonly encoding?: EncodingType;
@default 'hex'
*/
readonly encoding?: EncodingType;
/**
Values: `md5` `sha1` `sha256` `sha512` _([Platform dependent](https://nodejs.org/api/crypto.html#crypto_crypto_createhash_algorithm_options))_
_The `md5` algorithm is good for [file revving](https://github.com/sindresorhus/rev-hash), but you should never use `md5` or `sha1` for anything sensitive. [They're insecure.](https://security.googleblog.com/2014/09/gradually-sunsetting-sha-1.html)_
@default 'sha512'
*/
readonly algorithm?: AlgorithmName;
}
}
declare const hasha: {
/**
Calculate the hash for a `string`, `Buffer`, or an array thereof.
The available values are [platform dependent](https://nodejs.org/api/crypto.html#crypto_crypto_createhash_algorithm_options).
@param input - Data you want to hash.
_The `md5` algorithm is good for [file revving](https://github.com/sindresorhus/rev-hash), but you should never use `md5` or `sha1` for anything sensitive. [They're insecure.](https://security.googleblog.com/2014/09/gradually-sunsetting-sha-1.html)_
While strings are supported you should prefer buffers as they're faster to hash. Although if you already have a string you should not convert it to a buffer.
@default 'sha512'
*/
readonly algorithm?: HashAlgorithm;
};
Pass an array instead of concatenating strings and/or buffers. The output is the same, but arrays do not incur the overhead of concatenation.
/**
Calculate the hash of a `string`, `Uint8Array`, or an array thereof.
@returns A hash.
@param input - The value to hash.
@returns A hash.
@example
```
import hasha = require('hasha');
The operation is executed using `worker_threads`. A thread is lazily spawned on the first operation and lives until the end of the program execution. It's unrefed, so it won't keep the process alive.
hasha('unicorn');
//=> 'e233b19aabc7d5e53826fb734d1222f1f0444c3a3fc67ff4af370a66e7cadd2cb24009f1bc86f0bed12ca5fcb226145ad10fc5f650f6ef0959f8aadc5a594b27'
```
*/
(input: hasha.HashaInput): string;
(
input: hasha.HashaInput,
options: hasha.Options<hasha.ToStringEncoding>
): string;
(input: hasha.HashaInput, options: hasha.Options<'buffer'>): Buffer;
While strings are supported you should prefer buffers as they're faster to hash. Although if you already have a string you should not convert it to a buffer.
/**
Asynchronously calculate the hash for a `string`, `Buffer`, or an array thereof.
Pass an array instead of concatenating strings and/or buffers. The output is the same, but arrays do not incur the overhead of concatenation.
In Node.js 12 or later, the operation is executed using `worker_threads`. A thread is lazily spawned on the first operation and lives until the end of the program execution. It's unrefed, so it won't keep the process alive.
@example
```
import {hash} from 'hasha';
@param input - Data you want to hash.
await hash('unicorn');
//=> 'e233b19aabc7d5e53826fb734d1222f1f0444c3a3fc67ff4af370a66e7cadd2cb24009f1bc86f0bed12ca5fcb226145ad10fc5f650f6ef0959f8aadc5a594b27'
```
*/
export function hash(input: HashInput, options?: Options<StringEncoding>): Promise<string>;
export function hash(input: HashInput, options?: Options<'buffer'>): Promise<Buffer>;
While strings are supported you should prefer buffers as they're faster to hash. Although if you already have a string you should not convert it to a buffer.
/**
Synchronously calculate the hash of a `string`, `Uint8Array`, or an array thereof.
Pass an array instead of concatenating strings and/or buffers. The output is the same, but arrays do not incur the overhead of concatenation.
@param input - The value to hash.
@returns A hash.
@returns A hash.
While strings are supported you should prefer buffers as they're faster to hash. Although if you already have a string you should not convert it to a buffer.
@example
```
import hasha = require('hasha');
Pass an array instead of concatenating strings and/or buffers. The output is the same, but arrays do not incur the overhead of concatenation.
(async () => {
console.log(await hasha.async('unicorn'));
//=> 'e233b19aabc7d5e53826fb734d1222f1f0444c3a3fc67ff4af370a66e7cadd2cb24009f1bc86f0bed12ca5fcb226145ad10fc5f650f6ef0959f8aadc5a594b27'
})();
```
*/
async(input: hasha.HashaInput): Promise<string>;
async(
input: hasha.HashaInput,
options: hasha.Options<hasha.ToStringEncoding>
): Promise<string>;
async(input: hasha.HashaInput, options: hasha.Options<'buffer'>): Promise<Buffer>;
@example
```
import {hashSync} from 'hasha';
/**
Create a [hash transform stream](https://nodejs.org/api/crypto.html#crypto_class_hash).
hashSync('unicorn');
//=> 'e233b19aabc7d5e53826fb734d1222f1f0444c3a3fc67ff4af370a66e7cadd2cb24009f1bc86f0bed12ca5fcb226145ad10fc5f650f6ef0959f8aadc5a594b27'
```
*/
export function hashSync(input: HashSyncInput, options?: Options<StringEncoding>): string;
export function hashSync(input: HashSyncInput, options?: Options<'buffer'>): Buffer;
@returns The created hash transform stream.
/**
Calculate the hash of a file.
@example
```
import hasha = require('hasha');
@param filePath - Path to a file you want to hash.
@returns The calculated file hash.
// Hash the process input and output the hash sum
process.stdin.pipe(hasha.stream()).pipe(process.stdout);
```
*/
stream(options?: hasha.Options<hasha.HashaEncoding>): Hash;
The operation is executed using `worker_threads`. A thread is lazily spawned on the first operation and lives until the end of the program execution. It's unrefed, so it won't keep the process alive.
/**
Calculate the hash for a stream.
@example
```
import {hashFile} from 'hasha';
@param stream - A stream you want to hash.
@returns The calculated hash.
*/
fromStream(stream: NodeJS.ReadableStream): Promise<string>;
fromStream(
stream: NodeJS.ReadableStream,
options?: hasha.Options<hasha.ToStringEncoding>
): Promise<string>;
fromStream(
stream: NodeJS.ReadableStream,
options?: hasha.Options<'buffer'>
): Promise<Buffer>;
// Get the MD5 hash of an image
await hashFile('unicorn.png', {algorithm: 'md5'});
//=> '1abcb33beeb811dca15f0ac3e47b88d9'
```
*/
export function hashFile(filePath: string, options?: Options<StringEncoding>): Promise<string>;
export function hashFile(filePath: string, options?: Options<'buffer'>): Promise<Buffer>;
/**
Calculate the hash for a file.
/**
Synchronously calculate the hash of a file.
In Node.js 12 or later, the operation is executed using `worker_threads`. A thread is lazily spawned on the first operation and lives until the end of the program execution. It's unrefed, so it won't keep the process alive.
@param filePath - Path to a file you want to hash.
@returns The calculated file hash.
@param filePath - Path to a file you want to hash.
@returns The calculated file hash.
@example
```
import {hashFileSync} from 'hasha';
@example
```
import hasha = require('hasha');
// Get the MD5 hash of an image
hashFileSync('unicorn.png', {algorithm: 'md5'});
//=> '1abcb33beeb811dca15f0ac3e47b88d9'
```
*/
export function hashFileSync(filePath: string, options?: Options<StringEncoding>): string;
export function hashFileSync(filePath: string, options?: Options<'buffer'>): Buffer;
(async () => {
// Get the MD5 hash of an image
const hash = await hasha.fromFile('unicorn.png', {algorithm: 'md5'});
/**
Create a [hash transform stream](https://nodejs.org/api/crypto.html#crypto_class_hash).
console.log(hash);
//=> '1abcb33beeb811dca15f0ac3e47b88d9'
})();
```
*/
fromFile(filePath: string): Promise<string>;
fromFile(
filePath: string,
options: hasha.Options<hasha.ToStringEncoding>
): Promise<string>;
fromFile(
filePath: string,
options: hasha.Options<'buffer'>
): Promise<Buffer>;
@example
```
import {hashingStream} from 'hasha';
/**
Synchronously calculate the hash for a file.
@param filePath - Path to a file you want to hash.
@returns The calculated file hash.
*/
fromFileSync(filePath: string): string;
fromFileSync(
filePath: string,
options: hasha.Options<hasha.ToStringEncoding>
): string;
fromFileSync(filePath: string, options: hasha.Options<'buffer'>): Buffer;
};
export = hasha;
// Hash the process input and output the hash sum
process.stdin.pipe(hashingStream()).pipe(process.stdout);
```
*/
export function hashingStream(options?: Options): Hash;

@@ -1,11 +0,9 @@

'use strict';
const fs = require('fs');
const path = require('path');
const crypto = require('crypto');
const isStream = require('is-stream');
import fs from 'node:fs';
import crypto from 'node:crypto';
import {isStream} from 'is-stream';
const {Worker} = (() => {
const {Worker} = await (async () => {
try {
return require('worker_threads');
} catch (_) {
return await import('node:worker_threads');
} catch {
return {};

@@ -32,3 +30,3 @@ }

const createWorker = () => {
worker = new Worker(path.join(__dirname, 'thread.js'));
worker = new Worker(new URL('thread.js', import.meta.url));

@@ -56,3 +54,3 @@ worker.on('message', message => {

const taskWorker = (method, args, transferList) => new Promise((resolve, reject) => {
const taskWorker = (method, arguments_, transferList) => new Promise((resolve, reject) => {
const id = taskIdCounter++;

@@ -66,88 +64,91 @@ tasks.set(id, {resolve, reject});

worker.ref();
worker.postMessage({id, method, args}, transferList);
worker.postMessage({id, method, arguments_}, transferList);
});
const hasha = (input, options = {}) => {
let outputEncoding = options.encoding || 'hex';
export async function hash(input, options = {}) {
if (isStream(input)) {
return new Promise((resolve, reject) => {
// TODO: Use `stream.compose` and `.toArray()`.
input
.on('error', reject)
.pipe(hashingStream(options))
.on('error', reject)
.on('finish', function () {
resolve(this.read());
});
});
}
if (outputEncoding === 'buffer') {
outputEncoding = undefined;
if (Worker === undefined) {
return hashSync(input, options);
}
const hash = crypto.createHash(options.algorithm || 'sha512');
let {
encoding = 'hex',
algorithm = 'sha512',
} = options;
const update = buffer => {
const inputEncoding = typeof buffer === 'string' ? 'utf8' : undefined;
hash.update(buffer, inputEncoding);
};
if (Array.isArray(input)) {
input.forEach(update);
} else {
update(input);
if (encoding === 'buffer') {
encoding = undefined;
}
return hash.digest(outputEncoding);
};
const hash = await taskWorker('hash', [algorithm, input]);
hasha.stream = (options = {}) => {
let outputEncoding = options.encoding || 'hex';
if (outputEncoding === 'buffer') {
outputEncoding = undefined;
if (encoding === undefined) {
return Buffer.from(hash);
}
const stream = crypto.createHash(options.algorithm || 'sha512');
stream.setEncoding(outputEncoding);
return stream;
};
return Buffer.from(hash).toString(encoding);
}
hasha.fromStream = async (stream, options = {}) => {
if (!isStream(stream)) {
throw new TypeError('Expected a stream');
export function hashSync(input, {encoding = 'hex', algorithm = 'sha512'} = {}) {
if (encoding === 'buffer') {
encoding = undefined;
}
return new Promise((resolve, reject) => {
// TODO: Use `stream.pipeline` and `stream.finished` when targeting Node.js 10
stream
.on('error', reject)
.pipe(hasha.stream(options))
.on('error', reject)
.on('finish', function () {
resolve(this.read());
});
});
};
const hash = crypto.createHash(algorithm);
if (Worker === undefined) {
hasha.fromFile = async (filePath, options) => hasha.fromStream(fs.createReadStream(filePath), options);
hasha.async = async (input, options) => hasha(input, options);
} else {
hasha.fromFile = async (filePath, {algorithm = 'sha512', encoding = 'hex'} = {}) => {
const hash = await taskWorker('hashFile', [algorithm, filePath]);
const update = buffer => {
const inputEncoding = typeof buffer === 'string' ? 'utf8' : undefined;
hash.update(buffer, inputEncoding);
};
if (encoding === 'buffer') {
return Buffer.from(hash);
}
for (const element of [input].flat()) {
update(element);
}
return Buffer.from(hash).toString(encoding);
};
return hash.digest(encoding);
}
hasha.async = async (input, {algorithm = 'sha512', encoding = 'hex'} = {}) => {
if (encoding === 'buffer') {
encoding = undefined;
}
export async function hashFile(filePath, options = {}) {
if (Worker === undefined) {
return hash(fs.createReadStream(filePath), options);
}
const hash = await taskWorker('hash', [algorithm, input]);
const {
encoding = 'hex',
algorithm = 'sha512',
} = options;
if (encoding === undefined) {
return Buffer.from(hash);
}
const hash = await taskWorker('hashFile', [algorithm, filePath]);
return Buffer.from(hash).toString(encoding);
};
if (encoding === 'buffer') {
return Buffer.from(hash);
}
return Buffer.from(hash).toString(encoding);
}
hasha.fromFileSync = (filePath, options) => hasha(fs.readFileSync(filePath), options);
export function hashFileSync(filePath, options) {
return hashSync(fs.readFileSync(filePath), options);
}
module.exports = hasha;
export function hashingStream({encoding = 'hex', algorithm = 'sha512'} = {}) {
if (encoding === 'buffer') {
encoding = undefined;
}
const stream = crypto.createHash(algorithm);
stream.setEncoding(encoding);
return stream;
}
{
"name": "hasha",
"version": "5.2.2",
"version": "6.0.0",
"description": "Hashing made simple. Get the hash of a buffer/string/stream/file.",

@@ -13,4 +13,10 @@ "license": "MIT",

},
"type": "module",
"exports": {
"types": "./index.d.ts",
"default": "./index.js"
},
"sideEffects": false,
"engines": {
"node": ">=8"
"node": ">=18"
},

@@ -48,17 +54,18 @@ "scripts": {

"dependencies": {
"is-stream": "^2.0.0",
"type-fest": "^0.8.0"
"is-stream": "^3.0.0",
"type-fest": "^4.7.1"
},
"devDependencies": {
"@types/node": "^12.7.5",
"ava": "^2.4.0",
"proxyquire": "^2.1.0",
"tsd": "^0.8.0",
"xo": "^0.24.0"
"@types/node": "^20.9.0",
"ava": "^5.3.1",
"esmock": "^2.6.0",
"tsd": "^0.29.0",
"xo": "^0.56.0"
},
"xo": {
"rules": {
"import/no-unresolved": "off"
"unicorn/no-await-expression-member": "off",
"n/prefer-global/buffer": "off"
}
}
}

@@ -15,4 +15,2 @@ <h1 align="center">

[![Build Status](https://travis-ci.com/sindresorhus/hasha.svg?branch=master)](https://travis-ci.com/github/sindresorhus/hasha)
Convenience wrapper around the core [`crypto` Hash class](https://nodejs.org/api/crypto.html#crypto_crypto_createhash_algorithm) with simpler API and better defaults.

@@ -22,5 +20,5 @@

```sh
npm install hasha
```
$ npm install hasha
```

@@ -30,42 +28,20 @@ ## Usage

```js
const hasha = require('hasha');
import {hash} from 'hasha';
hasha('unicorn');
await hash('unicorn');
//=> 'e233b19aabc7d5e53826fb734d1222f1f0444c3a3fc67ff4af370a66e7cadd2cb24009f1bc86f0bed12ca5fcb226145ad10fc5f650f6ef0959f8aadc5a594b27'
```
```js
const hasha = require('hasha');
## API
(async () => {
console.log(await hasha.async('unicorn'));
//=> 'e233b19aabc7d5e53826fb734d1222f1f0444c3a3fc67ff4af370a66e7cadd2cb24009f1bc86f0bed12ca5fcb226145ad10fc5f650f6ef0959f8aadc5a594b27'
})();
```
See the Node.js [`crypto` docs](https://nodejs.org/api/crypto.html#crypto_crypto_createhash_algorithm_options) for more about hashing.
```js
const hasha = require('hasha');
### hash(input, options?)
// Hash the process input and output the hash sum
process.stdin.pipe(hasha.stream()).pipe(process.stdout);
```
The operation is executed using `worker_threads`. A thread is lazily spawned on the first operation and lives until the end of the program execution. It's unrefed, so it won't keep the process alive.
```js
const hasha = require('hasha');
Returns a hash asynchronously.
(async () => {
// Get the MD5 hash of an image
const hash = await hasha.fromFile('unicorn.png', {algorithm: 'md5'});
### hashSync(input, options?)
console.log(hash);
//=> '1abcb33beeb811dca15f0ac3e47b88d9'
})();
```
## API
See the Node.js [`crypto` docs](https://nodejs.org/api/crypto.html#crypto_crypto_createhash_algorithm_options) for more about hashing.
### hasha(input, options?)
Returns a hash.

@@ -75,5 +51,5 @@

Type: `Buffer | string | Array<Buffer | string>`
Type: `Uint8Array | string | Array<Uint8Array | string> | NodeJS.ReadableStream` *(`NodeJS.ReadableStream` is not available in `hashSync`)*
Buffer you want to hash.
The value to hash.

@@ -94,3 +70,3 @@ While strings are supported you should prefer buffers as they're faster to hash. Although if you already have a string you should not convert it to a buffer.

Encoding of the returned hash.
The encoding of the returned hash.

@@ -105,26 +81,39 @@ ##### algorithm

### hasha.async(input, options?)
### hashFile(filePath, options?)
In Node.js 12 or later, the operation is executed using `worker_threads`. A thread is lazily spawned on the first operation and lives until the end of the program execution. It's unrefed, so it won't keep the process alive.
The operation is executed using `worker_threads`. A thread is lazily spawned on the first operation and lives until the end of the program execution. It's unrefed, so it won't keep the process alive.
Returns a hash asynchronously.
Returns a `Promise` for the calculated file hash.
### hasha.stream(options?)
```js
import {hashFile} from 'hasha';
Returns a [hash transform stream](https://nodejs.org/api/crypto.html#crypto_class_hash).
// Get the MD5 hash of an image
await hashFile('unicorn.png', {algorithm: 'md5'});
//=> '1abcb33beeb811dca15f0ac3e47b88d9'
```
### hasha.fromStream(stream, options?)
### hashFileSync(filePath, options?)
Returns a `Promise` for the calculated hash.
Returns the calculated file hash.
### hasha.fromFile(filepath, options?)
```js
import {hashFileSync} from 'hasha';
In Node.js 12 or later, the operation is executed using `worker_threads`. A thread is lazily spawned on the first operation and lives until the end of the program execution. It's unrefed, so it won't keep the process alive.
// Get the MD5 hash of an image
hashFileSync('unicorn.png', {algorithm: 'md5'});
//=> '1abcb33beeb811dca15f0ac3e47b88d9'
```
Returns a `Promise` for the calculated file hash.
### hashingStream(options?)
### hasha.fromFileSync(filepath, options?)
Returns a [hash transform stream](https://nodejs.org/api/crypto.html#crypto_class_hash).
Returns the calculated file hash.
```js
import {hashingStream} from 'hasha';
// Hash the process input and output the hash sum
process.stdin.pipe(hashingStream()).pipe(process.stdout);
```
## Related

@@ -134,3 +123,3 @@

- [crypto-hash](https://github.com/sindresorhus/crypto-hash) - Tiny hashing module that uses the native crypto API in Node.js and the browser
- [hash-obj](https://github.com/sindresorhus/hash-obj) - Get the hash of an object
- [hash-object](https://github.com/sindresorhus/hash-object) - Get the hash of an object
- [md5-hex](https://github.com/sindresorhus/md5-hex) - Create a MD5 hash with hex encoding

@@ -1,5 +0,4 @@

'use strict';
const fs = require('fs');
const crypto = require('crypto');
const {parentPort} = require('worker_threads');
import fs from 'node:fs';
import crypto from 'node:crypto';
import {parentPort} from 'node:worker_threads';

@@ -10,3 +9,3 @@ const handlers = {

fs.createReadStream(filePath)
// TODO: Use `Stream.pipeline` when targeting Node.js 12.
// TODO: Use `Stream.pipeline`.
.on('error', reject)

@@ -20,11 +19,7 @@ .pipe(hasher)

}),
hash: async (algorithm, input) => {
async hash(algorithm, input) {
const hasher = crypto.createHash(algorithm);
if (Array.isArray(input)) {
for (const part of input) {
hasher.update(part);
}
} else {
hasher.update(input);
for (const part of [input].flat()) {
hasher.update(part);
}

@@ -34,3 +29,3 @@

return {value: buffer, transferList: [buffer]};
}
},
};

@@ -40,3 +35,3 @@

try {
const {method, args} = message;
const {method, arguments_} = message;
const handler = handlers[method];

@@ -48,3 +43,3 @@

const {value, transferList} = await handler(...args);
const {value, transferList} = await handler(...arguments_);
parentPort.postMessage({id: message.id, value}, transferList);

@@ -51,0 +46,0 @@ } catch (error) {

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc