Skip to content

Instantly share code, notes, and snippets.

@bluwy
Last active December 20, 2022 06:35
Show Gist options
  • Save bluwy/3660a23295c11c8f6d972b20006509f1 to your computer and use it in GitHub Desktop.
Save bluwy/3660a23295c11c8f6d972b20006509f1 to your computer and use it in GitHub Desktop.
fs access perf test
import fs from 'fs'
let timer = process.hrtime()
for (let i = 0; i < 1000; i++) {
for (let j = 0; j < 1000; j++) {
let path = './non/' + i + '/' + j + '.txt'
// fs.existsSync(path)
// isFileReadable(path)
// isFileStat(path)
// isFileStatFast(path)
isFileStatFastSafe(path)
}
}
let delta = process.hrtime(timer)
console.log('took', format(delta))
function isFileReadable(filename) {
try {
fs.accessSync(filename, fs.constants.R_OK)
return true
} catch {
return false
}
}
function isFileStat(filename) {
try {
fs.statSync(filename)
return true
} catch {
return false
}
}
function isFileStatFast(filename) {
return !!fs.statSync(filename, { throwIfNoEntry: false })
}
const canRead =
fs.constants.S_IRUSR | fs.constants.S_IRGRP | fs.constants.S_IROTH
function isFileStatFastSafe(filename) {
const stat = fs.statSync(filename, { throwIfNoEntry: false })
return stat ? !!(stat.mode & canRead) : false
}
function format(arr) {
let num = Math.round(arr[1] / 1e6)
if (arr[0] > 0) return (arr[0] + num / 1e3).toFixed(2) + 's'
return `${num}ms`
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment