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