Is it possible to list files in directory with bun?
Looked into the docs for the bun utilities but can't seem to find it. Perhaps I'm missing something.
Is it possible to list files in directory with bun?
Looked into the docs for the bun utilities but can't seem to find it. Perhaps I'm missing something.
On
As of Q3 2023, Bun does not yet provide its own fully-featured filesystem library - their documentation says to use their reimplementation of NodeJS's fs library:
https://bun.sh/docs/api/file-io
[...]
For operations that are not yet available with Bun.file, such as mkdir, you can use Bun's nearly complete implementation of the node:fs module.
Bun's reimplementation is documented at https://bun.sh/docs/runtime/nodejs-apis#node-fs
To get a list of files in a directory with Bun, this should work (untested):
import { readdir } from 'node:fs/promises';
import { join } from 'node:path';
/**
* @param {string | Buffer | URL} directoryPath
* @returns {Promise<string[]>} - Array of long file paths
*/
async function getFiles( directoryPath ) {
try {
const fileNames = await readdir( directoryPath ); // returns a JS array of just short/local file-names, not paths.
const filePaths = fileNames.map( fn => join( directoryPath, fn ) );
return filePaths;
}
catch (err) {
console.error( err ); // depending on your application, this `catch` block (as-is) may be inappropriate; consider instead, either not-catching and/or re-throwing a new Error with the previous err attached.
}
}
Actually you can
More in the documentation: https://bun.sh/docs/api/glob