PHP's sha1_file in TypeScript

✓ Verified: PHP 8.3
Examples tested against actual runtime. CI re-verifies continuously. Only documented examples are tested.

How to use

Install via yarn add locutus and import: import { sha1_file } from 'locutus/php/strings/sha1_file'.

Or with CommonJS: const { sha1_file } = require('locutus/php/strings/sha1_file')

Use a bundler that supports tree-shaking so you only ship the functions you actually use. Vite, webpack, Rollup, and Parcel all handle this. For server-side use this is less of a concern.

Examples

These examples are extracted from test cases that automatically verify our functions against their native counterparts.

#codeexpected result
1sha1_file('test/never-change.txt')'0ea65a1f4b4d69712affc58240932f3eb8a2af66'

Notes

  • Relies on file_get_contents which does not work in the browser, so Node only.

  • Keep in mind that in accordance with PHP, the whole file is buffered and then hashed. We’d recommend Node’s native crypto modules for faster and more efficient hashing

Dependencies

This function uses the following Locutus functions:

Here's what our current TypeScript equivalent to PHP's sha1_file looks like.

import { file_get_contents as fileGetContents } from '../filesystem/file_get_contents.ts'
import { sha1 } from '../strings/sha1.ts'

export function sha1_file(str_filename: string): string | false {
// discuss at: https://locutus.io/php/sha1_file/
// parity verified: PHP 8.3
// original by: Kevin van Zonneveld (https://kvz.io)
// note 1: Relies on file_get_contents which does not work in the browser, so Node only.
// note 2: Keep in mind that in accordance with PHP, the whole file is buffered and then
// note 2: hashed. We'd recommend Node's native crypto modules for faster and more
// note 2: efficient hashing
// example 1: sha1_file('test/never-change.txt')
// returns 1: '0ea65a1f4b4d69712affc58240932f3eb8a2af66'

const buf = fileGetContents(str_filename)

if (buf === false) {
return false
}

return sha1(buf)
}

Improve this function

Locutus is a community effort following The McDonald's Theory: we ship first iterations, hoping others will improve them. If you see something that could be better, we'd love your contribution.

View on GitHub · Edit on GitHub · View Raw


« More PHP strings functions


Star