Skip to content

Like `fs.promises.readdir()`, but sorts the result based on `String#localeCompare()`

License

Notifications You must be signed in to change notification settings

shinnn/readdir-sorted

Repository files navigation

readdir-sorted

npm version Build Status codecov

Like fs.promise.readdir() but sorts the result based on String#localeCompare()

const readdirSorted = require('readdir-sorted');

(async () => {
  await readdirSorted('.'); /* => [
    '.editorconfig',
    '.gitattributes',
    '.gitignore',
    '.travis.yml',
    'index.js',
    'LICENSE',
    'package.json',
    'README.md',
    'test'
  ] */
})();

Installation

Use npm.

npm install readdir-sorted

API

const readdirSorted = require('readdir-sorted');

readdirSorted(path [, options])

path: string | Buffer | URL (directory path)
options: Object
Return: Promise<string[]|Buffer[]|fs.Dirent[]>

It returns a result of fs.promises.readdir() with sorting entries based on String#localeCompare().

Options

options.encoding and options.withFileTypes

Both will be passed to fs.promises.readdir().

(async () => {
  await readdirSorted('example');
  //=> ['directory', 'file.txt', 'symlink']

  await readdirSorted('example', {
    encoding: 'base64',
    withFileTypes: true
  });
  /* => [
    Dirent { name: 'ZGlyZWN0b3J5', [Symbol(type)]: 2 },
    Dirent { name: 'aW5kZXguanM=', [Symbol(type)]: 1 },
    Dirent { name: 'c3ltbGluaw==', [Symbol(type)]: 3 }
  ] */
})();

Other options

locale property will be passed to the second argument of String#localeCompare(), and the rest will be used in the third argument.

(async () => {
  await readdirSorted('/path/to/dir');
  //=> ['10', '2', 'ä', 'z']

  await readdirSorted('/path/to/dir', {
    locale: 'sv',
    numeric: true
  });
  //=> ['2', '10', 'z', 'ä']
})();

License

ISC License © 2017 - 2019 Watanabe Shinnosuke

About

Like `fs.promises.readdir()`, but sorts the result based on `String#localeCompare()`

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published