|
| 1 | +# @npmcli/fs |
| 2 | + |
| 3 | +polyfills, and extensions, of the core `fs` module. |
| 4 | + |
| 5 | +## Features |
| 6 | + |
| 7 | +- all exposed functions return promises |
| 8 | +- `fs.rm` polyfill for node versions < 14.14.0 |
| 9 | +- `fs.mkdir` polyfill adding support for the `recursive` and `force` options in node versions < 10.12.0 |
| 10 | +- `fs.copyFile` extended to accept an `owner` option |
| 11 | +- `fs.mkdir` extended to accept an `owner` option |
| 12 | +- `fs.mkdtemp` extended to accept an `owner` option |
| 13 | +- `fs.writeFile` extended to accept an `owner` option |
| 14 | +- `fs.withTempDir` added |
| 15 | + |
| 16 | +## The `owner` option |
| 17 | + |
| 18 | +The `copyFile`, `mkdir`, `mkdtemp`, `writeFile`, and `withTempDir` functions |
| 19 | +all accept a new `owner` property in their options. It can be used in two ways: |
| 20 | + |
| 21 | +- `{ owner: { uid: 100, gid: 100 } }` - set the `uid` and `gid` explicitly |
| 22 | +- `{ owner: 100 }` - use one value, will set both `uid` and `gid` the same |
| 23 | + |
| 24 | +The special string `'inherit'` may be passed instead of a number, which will |
| 25 | +cause this module to automatically determine the correct `uid` and/or `gid` |
| 26 | +from the nearest existing parent directory of the target. |
| 27 | + |
| 28 | +## `fs.withTempDir(root, fn, options) -> Promise` |
| 29 | + |
| 30 | +### Parameters |
| 31 | + |
| 32 | +- `root`: the directory in which to create the temporary directory |
| 33 | +- `fn`: a function that will be called with the path to the temporary directory |
| 34 | +- `options` |
| 35 | + - `tmpPrefix`: a prefix to be used in the generated directory name |
| 36 | + |
| 37 | +### Usage |
| 38 | + |
| 39 | +The `withTempDir` function creates a temporary directory, runs the provided |
| 40 | +function (`fn`), then removes the temporary directory and resolves or rejects |
| 41 | +based on the result of `fn`. |
| 42 | + |
| 43 | +```js |
| 44 | +const fs = require('@npmcli/fs') |
| 45 | +const os = require('os') |
| 46 | + |
| 47 | +// this function will be called with the full path to the temporary directory |
| 48 | +// it is called with `await` behind the scenes, so can be async if desired. |
| 49 | +const myFunction = async (tempPath) => { |
| 50 | + return 'done!' |
| 51 | +} |
| 52 | + |
| 53 | +const main = async () => { |
| 54 | + const result = await fs.withTempDir(os.tmpdir(), myFunction) |
| 55 | + // result === 'done!' |
| 56 | +} |
| 57 | + |
| 58 | +main() |
| 59 | +``` |
0 commit comments