### Write file with async/await, creating directories Source: https://github.com/jprichardson/node-fs-extra/blob/master/docs/outputFile.md Use this async/await example to write data to a file, ensuring directory creation. It leverages Promises internally for cleaner asynchronous code. Make sure fs-extra is required. ```javascript const fs = require('fs-extra') const file = '/tmp/this/path/does/not/exist/file.txt' // With async/await: async function example (f) { try { await fs.outputFile(f, 'hello!') const data = await fs.readFile(f, 'utf8') console.log(data) // => hello! } catch (err) { console.error(err) } } example(file) ``` -------------------------------- ### Write JSON with Async/Await Source: https://github.com/jprichardson/node-fs-extra/blob/master/docs/outputJson.md An example of writing JSON data to a file using async/await syntax. This approach simplifies asynchronous operations, including directory creation and subsequent file reading. ```javascript const fs = require('fs-extra') const file = '/tmp/this/path/does/not/exist/file.json' // With async/await: async function example (f) { try { await fs.outputJson(f, {name: 'JP'}) const data = await fs.readJson(f) console.log(data.name) // => JP } catch (err) { console.error(err) } } example(file) ``` -------------------------------- ### Writing to a file with directory creation Source: https://github.com/jprichardson/node-fs-extra/blob/master/docs/outputFile-sync.md Use this snippet to write data to a file. It automatically creates any necessary parent directories if they do not exist. Ensure 'fs-extra' is installed and required. ```javascript const fs = require('fs-extra') const file = '/tmp/this/path/does/not/exist/file.txt' fs.outputFileSync(file, 'hello!') const data = fs.readFileSync(file, 'utf8') console.log(data) // => hello! ``` -------------------------------- ### fs.writev() with async/await Source: https://github.com/jprichardson/node-fs-extra/blob/master/docs/fs-read-write-writev.md Example of using fs.writev() with async/await. Destructures the results to get bytesWritten and buffers. ```javascript // With async/await: async function example () { const { bytesWritten, buffers } = await fs.writev(fd, buffers, position) } ``` -------------------------------- ### fs.write() with Promises Source: https://github.com/jprichardson/node-fs-extra/blob/master/docs/fs-read-write-writev.md Example of using fs.write() with Promises. The callback receives 3 arguments: bytesWritten and buffer. ```javascript // With Promises: fs.write(fd, buffer, offset, length, position) .then(results => { console.log(results) // { bytesWritten: 20, buffer: } }) ``` -------------------------------- ### fs.write() with async/await Source: https://github.com/jprichardson/node-fs-extra/blob/master/docs/fs-read-write-writev.md Example of using fs.write() with async/await. Destructures the results to get bytesWritten and buffer. ```javascript // With async/await: async function example () { const { bytesWritten, buffer } = await fs.write(fd, Buffer.alloc(length), offset, length, position) } ``` -------------------------------- ### fs.read() with Promises Source: https://github.com/jprichardson/node-fs-extra/blob/master/docs/fs-read-write-writev.md Example of using fs.read() with Promises. The callback receives 3 arguments: bytesRead and buffer. ```javascript // With Promises: fs.read(fd, buffer, offset, length, position) .then(results => { console.log(results) // { bytesRead: 20, buffer: } }) ``` -------------------------------- ### fs.read() with async/await Source: https://github.com/jprichardson/node-fs-extra/blob/master/docs/fs-read-write-writev.md Example of using fs.read() with async/await. Destructures the results to get bytesRead and buffer. ```javascript // With async/await: async function example () { const { bytesRead, buffer } = await fs.read(fd, Buffer.alloc(length), offset, length, position) } ``` -------------------------------- ### Synchronously Output JSON with Directory Creation Source: https://github.com/jprichardson/node-fs-extra/blob/master/docs/outputJson-sync.md Use outputJsonSync to write a JSON object to a file. It will create any necessary parent directories if they do not already exist. This example demonstrates writing an object and then reading it back. ```javascript const fs = require('fs-extra') const file = '/tmp/this/path/does/not/exist/file.json' fs.outputJsonSync(file, {name: 'JP'}) const data = fs.readJsonSync(file) console.log(data.name) // => JP ``` -------------------------------- ### Read JSON with Invalid JSON Handling Source: https://github.com/jprichardson/node-fs-extra/blob/master/docs/readJson-sync.md This example demonstrates how to use the `throws: false` option with `readJsonSync` to prevent errors when the JSON file content is invalid. Instead of throwing an error, it returns `null`. ```javascript const fs = require('fs-extra') const file = '/tmp/some-invalid.json' const data = '{not valid JSON' fs.writeFileSync(file, data) const obj = fs.readJsonSync(file, { throws: false }) console.log(obj) // => null ``` -------------------------------- ### Creating a Directory Synchronously Source: https://github.com/jprichardson/node-fs-extra/blob/master/docs/ensureDir-sync.md Use `ensureDirSync` to create a directory and its parent directories if they do not exist. This is a synchronous operation. ```javascript const fs = require('fs-extra') const dir = '/tmp/this/path/does/not/exist' const desiredMode = 0o2775 const options = { mode: 0o2775 } fs.ensureDirSync(dir) // dir has now been created, including the directory it is to be placed in fs.ensureDirSync(dir, desiredMode) // dir has now been created, including the directory it is to be placed in with permission 0o2775 fs.ensureDirSync(dir, options) // dir has now been created, including the directory it is to be placed in with permission 0o2775 ``` -------------------------------- ### Write file with Promises, creating directories Source: https://github.com/jprichardson/node-fs-extra/blob/master/docs/outputFile.md This snippet demonstrates writing to a file using Promises. It automatically creates necessary parent directories and returns a Promise that resolves upon successful write. fs-extra must be imported. ```javascript const fs = require('fs-extra') const file = '/tmp/this/path/does/not/exist/file.txt' // With Promises: fs.outputFile(file, 'hello!') .then(() => fs.readFile(file, 'utf8')) .then(data => { console.log(data) // => hello! }) .catch(err => { console.error(err) }) ``` -------------------------------- ### Ensure Directory Exists (Async/Await) Source: https://github.com/jprichardson/node-fs-extra/blob/master/docs/ensureDir.md Use this snippet to ensure a directory exists using async/await syntax. The directory and any parent directories will be created if they don't exist. ```javascript const fs = require('fs-extra') const dir = '/tmp/this/path/does/not/exist' // With async/await: async function example (directory) { try { await fs.ensureDir(directory) console.log('success!') } catch (err) { console.error(err) } } example(dir) ``` -------------------------------- ### Map Network Drive on Windows Source: https://github.com/jprichardson/node-fs-extra/blob/master/README.md Command to map a network drive on Windows for testing purposes. Requires running Node.js command prompt as Administrator. ```bash net use z: "\\vmware-host\Shared Folders" ``` -------------------------------- ### Copy File with Async/Await Source: https://github.com/jprichardson/node-fs-extra/blob/master/docs/copy.md This snippet shows how to copy a file using async/await syntax, providing a more synchronous-looking approach to asynchronous operations with try/catch for error handling. ```javascript // With async/await: async function example () { try { await fs.copy('/tmp/myfile', '/tmp/mynewfile') console.log('success!') } catch (err) { console.error(err) } } example() ``` -------------------------------- ### Ensure Directory Exists (Promises) Source: https://github.com/jprichardson/node-fs-extra/blob/master/docs/ensureDir.md Use this snippet to ensure a directory exists using Promises. The directory and any parent directories will be created if they don't exist. ```javascript const fs = require('fs-extra') const dir = '/tmp/this/path/does/not/exist' // With Promises: fs.ensureDir(dir) .then(() => { console.log('success!') }) .catch(err => { console.error(err) }) ``` -------------------------------- ### outputFileSync(file, data[, options]) Source: https://github.com/jprichardson/node-fs-extra/blob/master/docs/outputFile-sync.md Writes data to a file, creating parent directories if they do not exist. This function is analogous to `writeFileSync` but includes the functionality to create parent directories. ```APIDOC ## outputFileSync(file, data[, options]) ### Description Writes data to a file, creating parent directories if they do not exist. This function is analogous to `writeFileSync` but includes the functionality to create parent directories. ### Parameters #### Path Parameters - **file** (String) - The path to the file to write. - **data** (String | Buffer | Uint8Array) - The data to write to the file. - **options** (Object | String) - Optional. The same options as `fs.writeFileSync()`. ``` -------------------------------- ### Ensure Directory Exists (Callback) Source: https://github.com/jprichardson/node-fs-extra/blob/master/docs/ensureDir.md Use this snippet to ensure a directory exists using a callback. The directory and any parent directories will be created if they don't exist. ```javascript const fs = require('fs-extra') const dir = '/tmp/this/path/does/not/exist' // With a callback: fs.ensureDir(dir, err => { console.log(err) // => null // dir has now been created, including the directory it is to be placed in }) ``` -------------------------------- ### Ensure File Sync Source: https://github.com/jprichardson/node-fs-extra/blob/master/docs/ensureFile-sync.md Use `ensureFileSync` to create a file and its parent directories synchronously. The file will not be modified if it already exists. ```javascript const fs = require('fs-extra') const file = '/tmp/this/path/does/not/exist/file.txt' fs.ensureFileSync(file) // file has now been created, including the directory it is to be placed in ``` -------------------------------- ### Write file with callback, creating directories Source: https://github.com/jprichardson/node-fs-extra/blob/master/docs/outputFile.md Use this snippet to write data to a file. It creates parent directories if they don't exist and handles the operation using a callback function. Ensure fs-extra is required. ```javascript const fs = require('fs-extra') const file = '/tmp/this/path/does/not/exist/file.txt' // With a callback: fs.outputFile(file, 'hello!', err => { console.log(err) // => null fs.readFile(file, 'utf8', (err, data) => { if (err) return console.error(err) console.log(data) // => hello! }) }) ``` -------------------------------- ### outputFile(file, data[, options][, callback]) Source: https://github.com/jprichardson/node-fs-extra/blob/master/docs/outputFile.md Writes data to a file. If the parent directory does not exist, it will be created. The `file` argument must be a file path. ```APIDOC ## outputFile(file, data[, options][, callback]) ### Description Writes data to a file. If the parent directory does not exist, it will be created. The `file` argument must be a file path. ### Parameters #### Path Parameters - **file** (String) - Required - The path to the file. - **data** (String | Buffer | Uint8Array) - Required - The data to write to the file. - **options** (Object | String) - Optional - The same options as `fs.writeFile()`. - **callback** (Function) - Optional - A callback function that is called with an error if one occurred. - **err** (Error) - An error object if an error occurred, otherwise null. ### Example: ```js const fs = require('fs-extra') const file = '/tmp/this/path/does/not/exist/file.txt' // With a callback: fs.outputFile(file, 'hello!', err => { console.log(err) // => null fs.readFile(file, 'utf8', (err, data) => { if (err) return console.error(err) console.log(data) // => hello! }) }) // With Promises: fs.outputFile(file, 'hello!') .then(() => fs.readFile(file, 'utf8')) .then(data => { console.log(data) // => hello! }) .catch(err => { console.error(err) }) // With async/await: async function example (f) { try { await fs.outputFile(f, 'hello!') const data = await fs.readFile(f, 'utf8') console.log(data) // => hello! } catch (err) { console.error(err) } } example(file) ``` ``` -------------------------------- ### emptyDir with async/await Source: https://github.com/jprichardson/node-fs-extra/blob/master/docs/emptyDir.md Use this snippet for a more synchronous-looking approach to asynchronous operations, leveraging async/await syntax for cleaner error handling with try/catch blocks. ```javascript const fs = require('fs-extra') // With async/await: async function example () { try { await fs.emptyDir('/tmp/some/dir') console.log('success!') } catch (err) { console.error(err) } } example() ``` -------------------------------- ### Copy File with Promises Source: https://github.com/jprichardson/node-fs-extra/blob/master/docs/copy.md This snippet demonstrates copying a file using Promises, allowing for cleaner asynchronous code with .then() and .catch() for success and error handling. ```javascript // With Promises: fs.copy('/tmp/myfile', '/tmp/mynewfile') .then(() => { console.log('success!') }) .catch(err => { console.error(err) }) ``` -------------------------------- ### Copy file using fs-extra (Async/Await) Source: https://github.com/jprichardson/node-fs-extra/blob/master/README.md Asynchronously copies a file from a source path to a destination path using async/await syntax. Errors are handled within a try-catch block. ```javascript async function copyFiles () { try { await fs.copy('/tmp/myfile', '/tmp/mynewfile') console.log('success!') } catch (err) { console.error(err) } } copyFiles() ``` -------------------------------- ### Copy file using fs-extra (Sync) Source: https://github.com/jprichardson/node-fs-extra/blob/master/README.md Synchronously copies a file from a source path to a destination path. Errors are thrown and must be caught using a try-catch block. ```javascript try { fs.copySync('/tmp/myfile', '/tmp/mynewfile') console.log('success!') } catch (err) { console.error(err) } ``` -------------------------------- ### Write JSON with Promises Source: https://github.com/jprichardson/node-fs-extra/blob/master/docs/outputJson.md This snippet demonstrates writing JSON data to a file using Promises. It handles directory creation automatically and includes reading the JSON back using Promise chaining. ```javascript const fs = require('fs-extra') const file = '/tmp/this/path/does/not/exist/file.json' // With Promises: fs.outputJson(file, {name: 'JP'}) .then(() => fs.readJson(file)) .then(data => { console.log(data.name) // => JP }) .catch(err => { console.error(err) }) ``` -------------------------------- ### Ensure Directory Exists with Mode (Async/Await) Source: https://github.com/jprichardson/node-fs-extra/blob/master/docs/ensureDir.md Ensures a directory exists with a specified mode using async/await. The mode is provided within an options object. ```javascript const fs = require('fs-extra') const dir = '/tmp/this/path/does/not/exist' const options = { mode: 0o2775 } // With async/await and an options object, containing mode: async function exampleMode (directory) { try { await fs.ensureDir(directory, options) console.log('success!') } catch (err) { console.error(err) } } exampleMode(dir) ``` -------------------------------- ### Ensure File Exists (Async/Await) Source: https://github.com/jprichardson/node-fs-extra/blob/master/docs/ensureFile.md Use this snippet with async/await for a more synchronous-looking way to ensure a file exists. It simplifies error handling with try/catch blocks. ```javascript const fs = require('fs-extra') const file = '/tmp/this/path/does/not/exist/file.txt' // With async/await: async function example (f) { try { await fs.ensureFile(f) console.log('success!') } catch (err) { console.error(err) } } example(file) ``` -------------------------------- ### Ensure Link with Async/Await Source: https://github.com/jprichardson/node-fs-extra/blob/master/docs/ensureLink.md Use this snippet to ensure a symbolic link exists using async/await. The parent directories will be created if they don't exist. This is the modern async/await pattern. ```javascript const fs = require('fs-extra') const srcPath = '/tmp/file.txt' const destPath = '/tmp/this/path/does/not/exist/file.txt' // With async/await: async function example (src, dest) { try { await fs.ensureLink(src, dest) console.log('success!') } catch (err) { console.error(err) } } example(srcPath, destPath) ``` -------------------------------- ### emptyDir with Promises Source: https://github.com/jprichardson/node-fs-extra/blob/master/docs/emptyDir.md Use this snippet when you prefer to handle asynchronous operations using Promises, chaining success and error handling with .then() and .catch(). ```javascript const fs = require('fs-extra') // With Promises: fs.emptyDir('/tmp/some/dir') .then(() => { console.log('success!') }) .catch(err => { console.error(err) }) ``` -------------------------------- ### Copy file using fs-extra (Async with Promises) Source: https://github.com/jprichardson/node-fs-extra/blob/master/README.md Asynchronously copies a file from a source path to a destination path using promises. Handles success and error logging. ```javascript fs.copy('/tmp/myfile', '/tmp/mynewfile') .then(() => console.log('success!')) .catch(err => console.error(err)) ``` -------------------------------- ### ensureDirSync(dir[, options]) Source: https://github.com/jprichardson/node-fs-extra/blob/master/docs/ensureDir-sync.md Ensures that the directory exists. If the directory structure does not exist, it is created. Options can specify the desired mode for the directory. ```APIDOC ## ensureDirSync(dir[, options]) ### Description Ensures that the directory exists. If the directory structure does not exist, it is created. Options can specify the desired mode for the directory. ### Method `ensureDirSync` (synchronous) ### Parameters #### Path Parameters - **dir** (string) - Required - The path to the directory to ensure exists. - **options** (integer | object) - Optional - Specifies the mode for the directory. Can be an integer representing the mode directly, or an object `{ mode: }`. ### Example: ```js const fs = require('fs-extra') const dir = '/tmp/this/path/does/not/exist' const desiredMode = 0o2775 const options = { mode: 0o2775 } fs.ensureDirSync(dir) fs.ensureDirSync(dir, desiredMode) fs.ensureDirSync(dir, options) ``` ``` -------------------------------- ### Copy file using fs-extra (Async with Callbacks) Source: https://github.com/jprichardson/node-fs-extra/blob/master/README.md Asynchronously copies a file from a source path to a destination path using a callback function. The callback handles potential errors. ```javascript fs.copy('/tmp/myfile', '/tmp/mynewfile', err => { if (err) return console.error(err) console.log('success!') }) ``` -------------------------------- ### Copy Directory with copySync Source: https://github.com/jprichardson/node-fs-extra/blob/master/docs/copy-sync.md Use copySync to copy an entire directory, including its contents, to a new location. ```javascript // copy directory, even if it has subdirectories or files fs.copySync('/tmp/mydir', '/tmp/mynewdir') ``` -------------------------------- ### move(src, dest[, options][, callback]) Source: https://github.com/jprichardson/node-fs-extra/blob/master/docs/move.md Moves a file or directory. It can handle moving across different devices and supports an overwrite option. The function can be used with callbacks, Promises, or async/await. ```APIDOC ## move(src, dest[, options][, callback]) ### Description Moves a file or directory, even across devices. ### Parameters #### Path Parameters - **src** (String) - The source file or directory path. - **dest** (String) - The destination path. Note: When `src` is a file, `dest` must be a file and when `src` is a directory, `dest` must be a directory. #### Options - **options** (Object) - **overwrite** (boolean) - Overwrite existing file or directory. Defaults to `false`. #### Callback - **callback** (Function) - **err** (Error) - An error object if an error occurs. ### Usage Examples **With a callback:** ```javascript const fs = require('fs-extra') const src = '/tmp/file.txt' const dest = '/tmp/this/path/does/not/exist/file.txt' fs.move(src, dest, err => { if (err) return console.error(err) console.log('success!') }) ``` **With Promises:** ```javascript const fs = require('fs-extra') const src = '/tmp/file.txt' const dest = '/tmp/this/path/does/not/exist/file.txt' fs.move(src, dest) .then(() => { console.log('success!') }) .catch(err => { console.error(err) }) ``` **With async/await:** ```javascript const fs = require('fs-extra') async function example (src, dest) { try { await fs.move(src, dest) console.log('success!') } catch (err) { console.error(err) } } example('/tmp/file.txt', '/tmp/this/path/does/not/exist/file.txt') ``` **Using `overwrite` option:** ```javascript const fs = require('fs-extra') fs.move('/tmp/somedir', '/tmp/may/already/exist/somedir', { overwrite: true }, err => { if (err) return console.error(err) console.log('success!') }) ``` ``` -------------------------------- ### emptyDir with Callback Source: https://github.com/jprichardson/node-fs-extra/blob/master/docs/emptyDir.md Use this snippet when you need to ensure a directory is empty and want to handle the operation's completion or error using a traditional callback function. ```javascript const fs = require('fs-extra') // assume this directory has a lot of files and folders // With a callback: fs.emptyDir('/tmp/some/dir', err => { if (err) return console.error(err) console.log('success!') }) ``` -------------------------------- ### Move File or Directory Synchronously with Overwrite Source: https://github.com/jprichardson/node-fs-extra/blob/master/docs/move-sync.md This snippet demonstrates how to move a file or directory synchronously, overwriting the destination if it already exists. Ensure the `overwrite` option is set to `true`. ```javascript const fs = require('fs-extra') fs.moveSync('/tmp/somedir', '/tmp/may/already/exist/somedir', { overwrite: true }) ``` -------------------------------- ### copy(src, dest[, options][, callback]) Source: https://github.com/jprichardson/node-fs-extra/blob/master/docs/copy.md Copies a file or directory. The directory can have contents. Supports callback, Promises, and async/await. ```APIDOC ## copy(src, dest[, options][, callback]) ### Description Copies a file or directory. If `src` is a directory, it copies its contents, not the directory itself. If `src` is a file, `dest` cannot be a directory. ### Parameters #### Path Parameters - **src** (String) - The source file or directory path. - **dest** (String) - The destination path. #### Options Object - **overwrite** (boolean): Overwrite existing file or directory. Defaults to `true`. If `false` and the destination exists, the operation silently fails unless `errorOnExist` is `true`. - **errorOnExist** (boolean): When `overwrite` is `false` and the destination exists, throw an error. Defaults to `false`. - **dereference** (boolean): Dereference symlinks. Defaults to `false`. - **preserveTimestamps** (boolean): When true, sets last modification and access times to those of the original source files. Defaults to `false`. - **filter** (Function): A function to filter copied files/directories. Return `true` to copy, `false` to ignore. Can also return a `Promise`. ### Callback - **err** (Error) - An error object if an error occurs. ### Examples #### Callback Example ```js const fs = require('fs-extra') fs.copy('/tmp/myfile', '/tmp/mynewfile', err => { if (err) return console.error(err) console.log('success!') }) ``` #### Promise Example ```js const fs = require('fs-extra') fs.copy('/tmp/myfile', '/tmp/mynewfile') .then(() => { console.log('success!') }) .catch(err => { console.error(err) }) ``` #### Async/Await Example ```js const fs = require('fs-extra') async function example () { try { await fs.copy('/tmp/myfile', '/tmp/mynewfile') console.log('success!') } catch (err) { console.error(err) } } example() ``` #### Using Filter Function ```js const fs = require('fs-extra') const filterFunc = (src, dest) => { // your logic here // it will be copied if return true } fs.copy('/tmp/mydir', '/tmp/mynewdir', { filter: filterFunc }, err => { if (err) return console.error(err) console.log('success!') }) ``` ``` -------------------------------- ### ensureFile(file[, callback]) Source: https://github.com/jprichardson/node-fs-extra/blob/master/docs/ensureFile.md Ensures that the file exists. If the file that is requested to be created is in directories that do not exist, these directories are created. If the file already exists, it is NOT MODIFIED. ```APIDOC ## ensureFile(file[, callback]) ### Description Ensures that the file exists. If the file that is requested to be created is in directories that do not exist, these directories are created. If the file already exists, it is **NOT MODIFIED**. ### Alias `createFile()` ### Parameters #### Path Parameters * **file** (string) - Required - The path to the file to ensure. * **callback** (Function) - Optional - A callback function that will be called with an error if one occurs. * **err** (Error) - An error object if an error occurred, otherwise null. ### Examples ```javascript const fs = require('fs-extra') const file = '/tmp/this/path/does/not/exist/file.txt' // With a callback: fs.ensureFile(file, err => { console.log(err) // => null // file has now been created, including the directory it is to be placed in }) // With Promises: fs.ensureFile(file) .then(() => { console.log('success!') }) .catch(err => { console.error(err) }) // With async/await: async function example (f) { try { await fs.ensureFile(f) console.log('success!') } catch (err) { console.error(err) } } example(file) ``` ``` -------------------------------- ### Copy Directory with Callback Source: https://github.com/jprichardson/node-fs-extra/blob/master/docs/copy.md Use this snippet to copy an entire directory, including its contents, using a callback. This method handles nested files and subdirectories. ```javascript fs.copy('/tmp/mydir', '/tmp/mynewdir', err => { if (err) return console.error(err) console.log('success!') }) // copies directory, even if it has subdirectories or files ``` -------------------------------- ### moveSync(src, dest[, options]) Source: https://github.com/jprichardson/node-fs-extra/blob/master/docs/move-sync.md Moves a file or directory synchronously, even across devices. It supports an optional overwrite flag. ```APIDOC ## moveSync(src, dest[, options]) ### Description Moves a file or directory synchronously, even across devices. It supports an optional overwrite flag. ### Parameters #### Path Parameters - **src** (String) - The source file or directory path. - **dest** (String) - The destination path. Note: When `src` is a file, `dest` must be a file and when `src` is a directory, `dest` must be a directory. #### Query Parameters - **options** (Object) - Optional configuration object. - **overwrite** (boolean) - Overwrite existing file or directory. Defaults to `false`. ### Example: ```javascript const fs = require('fs-extra') fs.moveSync('/tmp/somefile', '/tmp/does/not/exist/yet/somefile') fs.moveSync('/tmp/somedir', '/tmp/may/already/exist/somedir', { overwrite: true }) ``` ``` -------------------------------- ### Ensure Symbolic Link Exists Synchronously Source: https://github.com/jprichardson/node-fs-extra/blob/master/docs/ensureLink-sync.md Use this function to create a symbolic link. It will also create any necessary parent directories for the destination path if they do not already exist. This is a synchronous operation. ```javascript const fs = require('fs-extra') const srcPath = '/tmp/file.txt' const destPath = '/tmp/this/path/does/not/exist/file.txt' fs.ensureLinkSync(srcPath, destPath) // link has now been created, including the directory it is to be placed in ``` -------------------------------- ### Ensure Directory Exists with Mode (Callback) Source: https://github.com/jprichardson/node-fs-extra/blob/master/docs/ensureDir.md Ensures a directory exists with a specified mode using a callback. The mode is provided as an integer. ```javascript const fs = require('fs-extra') const dir = '/tmp/this/path/does/not/exist' const desiredMode = 0o2775 // With a callback and a mode integer fs.ensureDir(dir, desiredMode, err => { console.log(err) // => null // dir has now been created with mode 0o2775, including the directory it is to be placed in }) ``` -------------------------------- ### Ensure File Exists (Promise) Source: https://github.com/jprichardson/node-fs-extra/blob/master/docs/ensureFile.md Use this snippet when working with Promises to ensure a file exists. The Promise will resolve on success or reject on error. ```javascript const fs = require('fs-extra') const file = '/tmp/this/path/does/not/exist/file.txt' // With Promises: fs.ensureFile(file) .then(() => { console.log('success!') }) .catch(err => { console.error(err) }) ``` -------------------------------- ### Copy File with Callback Source: https://github.com/jprichardson/node-fs-extra/blob/master/docs/copy.md Use this snippet to copy a single file using a callback function for error handling. Ensure the source and destination paths are correctly specified. ```javascript const fs = require('fs-extra') // With a callback: fs.copy('/tmp/myfile', '/tmp/mynewfile', err => { if (err) return console.error(err) console.log('success!') }) // copies file ``` -------------------------------- ### Move File or Directory with Async/Await Source: https://github.com/jprichardson/node-fs-extra/blob/master/docs/move.md Moves a file or directory using async/await syntax within a try-catch block for modern asynchronous error handling. This approach is often preferred for its readability. ```javascript const fs = require('fs-extra') // With async/await: async function example (src, dest) { try { await fs.move(src, dest) console.log('success!') } catch (err) { console.error(err) } } example(src, dest) ``` -------------------------------- ### Ensure Directory Exists with Mode (Promises) Source: https://github.com/jprichardson/node-fs-extra/blob/master/docs/ensureDir.md Ensures a directory exists with a specified mode using Promises. The mode is provided as an integer. ```javascript const fs = require('fs-extra') const dir = '/tmp/this/path/does/not/exist' const desiredMode = 0o2775 // With Promises and a mode integer: fs.ensureDir(dir, desiredMode) .then(() => { console.log('success!') }) .catch(err => { console.error(err) }) ``` -------------------------------- ### Write JSON with Async/Await Source: https://github.com/jprichardson/node-fs-extra/blob/master/docs/writeJson.md Utilize this snippet for writing JSON files asynchronously using async/await syntax, providing a more synchronous-looking code structure for handling Promises. ```javascript // With async/await: async function example () { try { await fs.writeJson('./package.json', {name: 'fs-extra'}) console.log('success!') } catch (err) { console.error(err) } } example() ``` -------------------------------- ### Ensure Link with Promises Source: https://github.com/jprichardson/node-fs-extra/blob/master/docs/ensureLink.md Use this snippet to ensure a symbolic link exists using Promises. The parent directories will be created if they don't exist. This is the Promise-based approach. ```javascript const fs = require('fs-extra') const srcPath = '/tmp/file.txt' const destPath = '/tmp/this/path/does/not/exist/file.txt' // With Promises: fs.ensureLink(srcPath, destPath) .then(() => { console.log('success!') }) .catch(err => { console.error(err) }) ``` -------------------------------- ### Write JSON with Callback Source: https://github.com/jprichardson/node-fs-extra/blob/master/docs/outputJson.md Use this snippet to write JSON data to a file using a callback function. The directory will be created if it doesn't exist. It also demonstrates reading the JSON back. ```javascript const fs = require('fs-extra') const file = '/tmp/this/path/does/not/exist/file.json' // With a callback: fs.outputJson(file, {name: 'JP'}, err => { console.log(err) // => null fs.readJson(file, (err, data) => { if (err) return console.error(err) console.log(data.name) // => JP }) }) ``` -------------------------------- ### Move File or Directory with Promises Source: https://github.com/jprichardson/node-fs-extra/blob/master/docs/move.md Moves a file or directory using Promises for asynchronous handling. The .then() block executes on success, and .catch() handles any errors. ```javascript const fs = require('fs-extra') const src = '/tmp/file.txt' const dest = '/tmp/this/path/does/not/exist/file.txt' // With Promises: fs.move(src, dest) .then(() => { console.log('success!') }) .catch(err => { console.error(err) }) ``` -------------------------------- ### Import fs-extra in CommonJS Source: https://github.com/jprichardson/node-fs-extra/blob/master/README.md Demonstrates how to import the fs-extra module in a CommonJS environment. It can be aliased as 'fs' or 'fse'. ```javascript const fs = require('fs-extra') ``` ```javascript const fse = require('fs-extra') ``` -------------------------------- ### Ensure File Exists (Callback) Source: https://github.com/jprichardson/node-fs-extra/blob/master/docs/ensureFile.md Use this snippet when you need to ensure a file exists and want to handle the operation's completion or error using a traditional callback pattern. ```javascript const fs = require('fs-extra') const file = '/tmp/this/path/does/not/exist/file.txt' // With a callback: fs.ensureFile(file, err => { console.log(err) // => null // file has now been created, including the directory it is to be placed in }) ``` -------------------------------- ### outputJsonSync(file, object[, options]) Source: https://github.com/jprichardson/node-fs-extra/blob/master/docs/outputJson-sync.md Writes a JSON object to a file. If the directory for the file does not exist, it will be created. This method is an alias for `writeJsonSync` with the added functionality of creating directories. ```APIDOC ## outputJsonSync(file, object[, options]) ### Description Writes a JSON object to a file, creating any necessary parent directories if they do not exist. This is similar to `writeJsonSync` but ensures the directory structure is in place. ### Method `outputJsonSync` (synchronous) ### Parameters - **file** (``) - The path to the file where the JSON object will be written. - **object** (``) - The JSON object to write to the file. - **options** (``) - Optional. An object that can contain: - **spaces** (` | `) - Number of spaces for indentation or a string to use for indentation (e.g., '\t' for tabs). See [JSON.stringify space argument](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#The_space_argument) for more info. - **EOL** (``) - The End-Of-Line character to use. Defaults to `\n`. - **replacer** (` | `) - A function or array that alters the behavior of the stringification process. See [JSON.stringify replacer parameter](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#The_replacer_parameter). - Accepts additional options compatible with [`fs.writeFileSync()`](https://nodejs.org/api/fs.html#fs_fs_writefilesync_file_data_options). ### Example: ```javascript const fs = require('fs-extra') const file = '/tmp/this/path/does/not/exist/file.json' fs.outputJsonSync(file, {name: 'JP'}) const data = fs.readJsonSync(file) console.log(data.name) // => JP ``` ``` -------------------------------- ### Remove Directory with Callback Source: https://github.com/jprichardson/node-fs-extra/blob/master/docs/remove.md This snippet demonstrates removing a directory, including its contents, using a callback. Be cautious when specifying paths, as this operation can delete entire directory structures. ```javascript fs.remove('/home/jprichardson', err => { if (err) return console.error(err) console.log('success!') // I just deleted my entire HOME directory. }) ``` -------------------------------- ### ensureFileSync(file) Source: https://github.com/jprichardson/node-fs-extra/blob/master/docs/ensureFile-sync.md Ensures that the file exists. If the parent directories do not exist, they are created. If the file already exists, it is not modified. This is a synchronous operation. ```APIDOC ## ensureFileSync(file) ### Description Ensures that the file exists. If the file that is requested to be created is in directories that do not exist, these directories are created. If the file already exists, it is **NOT MODIFIED**. ### Alias `createFileSync()` ### Parameters #### Path Parameters - **file** (String) - Required - The path to the file to ensure exists. ### Request Example ```js const fs = require('fs-extra') const file = '/tmp/this/path/does/not/exist/file.txt' fs.ensureFileSync(file) // file has now been created, including the directory it is to be placed in ``` ``` -------------------------------- ### Ensure Symlink Sync Source: https://github.com/jprichardson/node-fs-extra/blob/master/docs/ensureSymlink-sync.md Use `ensureSymlinkSync` to create a symbolic link. This function will also create any necessary parent directories for the destination path. ```javascript const fs = require('fs-extra') const srcPath = '/tmp/file.txt' const destPath = '/tmp/this/path/does/not/exist/file.txt' fs.ensureSymlinkSync(srcPath, destPath) // symlink has now been created, including the directory it is to be placed in ``` -------------------------------- ### Copy File with copySync Source: https://github.com/jprichardson/node-fs-extra/blob/master/docs/copy-sync.md Use copySync to copy a single file from a source path to a destination path. ```javascript const fs = require('fs-extra') // copy file fs.copySync('/tmp/myfile', '/tmp/mynewfile') ``` -------------------------------- ### pathExists(file[, callback]) Source: https://github.com/jprichardson/node-fs-extra/blob/master/docs/pathExists.md Tests whether or not the given path exists by checking with the file system. Uses `fs.access` under the hood. ```APIDOC ## pathExists(file[, callback]) ### Description Tests whether or not the given path exists by checking with the file system. Like `fs.exists`, but with a normal callback signature (err, exists). Uses `fs.access` under the hood. ### Parameters #### Path Parameters - **file** (string) - Required - The path to check. - **callback** (Function) - Optional - A callback function that receives an error and a boolean indicating existence. - **err** (Error) - An error object if an error occurred. - **exists** (boolean) - True if the path exists, false otherwise. ### Request Example ```javascript const fs = require('fs-extra') const file = '/tmp/this/path/does/not/exist/file.txt' // With a callback: fs.pathExists(file, (err, exists) => { console.log(err) // => null console.log(exists) // => false }) // Promise usage: fs.pathExists(file) .then(exists => console.log(exists)) // => false // With async/await: async function example (f) { const exists = await fs.pathExists(f) console.log(exists) // => false } example(file) ``` ### Response #### Success Response - **exists** (boolean) - Indicates whether the path exists. ``` -------------------------------- ### Ensure Link with Callback Source: https://github.com/jprichardson/node-fs-extra/blob/master/docs/ensureLink.md Use this snippet to ensure a symbolic link exists using a callback function. The parent directories will be created if they don't exist. ```javascript const fs = require('fs-extra') const srcPath = '/tmp/file.txt' const destPath = '/tmp/this/path/does/not/exist/file.txt' // With a callback: fs.ensureLink(srcPath, destPath, err => { console.log(err) // => null // link has now been created, including the directory it is to be placed in }) ``` -------------------------------- ### Ensure Symlink with Promises Source: https://github.com/jprichardson/node-fs-extra/blob/master/docs/ensureSymlink.md This snippet demonstrates how to use `ensureSymlink` with Promises for cleaner asynchronous code. The Promise resolves on success and rejects on error. ```javascript const fs = require('fs-extra') const srcPath = '/tmp/file.txt' const destPath = '/tmp/this/path/does/not/exist/file.txt' // With Promises: fs.ensureSymlink(srcPath, destPath) .then(() => { console.log('success!') }) .catch(err => { console.error(err) }) ``` -------------------------------- ### copySync(src, dest[, options]) Source: https://github.com/jprichardson/node-fs-extra/blob/master/docs/copy-sync.md Copies a file or directory synchronously. If the source is a directory, it copies its contents. If the source is a file, the destination cannot be a directory. ```APIDOC ## copySync(src, dest[, options]) ### Description Copies a file or directory synchronously. The directory can have contents. If `src` is a directory, it copies everything inside that directory, not the entire directory itself. If `src` is a file, `dest` cannot be a directory. ### Parameters #### Path Parameters - **src** (string) - The source file or directory path. - **dest** (string) - The destination path. #### Options Object - **overwrite** (boolean) - Overwrite existing file or directory. Defaults to `true`. If set to `false` and the destination exists, the copy operation will silently fail unless `errorOnExist` is `true`. - **errorOnExist** (boolean) - When `overwrite` is `false` and the destination exists, throw an error. Defaults to `false`. - **dereference** (boolean) - Dereference symlinks. Defaults to `false`. - **preserveTimestamps** (boolean) - When true, sets last modification and access times to those of the original source files. When false, timestamp behavior is OS-dependent. Defaults to `false`. - **filter** (Function) - A function to filter copied files/directories. Return `true` to copy the item, `false` to ignore it. ### Examples Copy a file: ```javascript const fs = require('fs-extra') fs.copySync('/tmp/myfile', '/tmp/mynewfile') ``` Copy a directory: ```javascript const fs = require('fs-extra') fs.copySync('/tmp/mydir', '/tmp/mynewdir') ``` Using a filter function: ```javascript const fs = require('fs-extra') const filterFunc = (src, dest) => { // your logic here // it will be copied if return true } fs.copySync('/tmp/mydir', '/tmp/mynewdir', { filter: filterFunc }) ``` ``` -------------------------------- ### Ensure Symlink with Async/Await Source: https://github.com/jprichardson/node-fs-extra/blob/master/docs/ensureSymlink.md Utilize async/await for modern asynchronous programming with `ensureSymlink`. This approach provides a synchronous-like syntax for handling Promises. ```javascript const fs = require('fs-extra') const srcPath = '/tmp/file.txt' const destPath = '/tmp/this/path/does/not/exist/file.txt' // With async/await: async function example (src, dest) { try { await fs.ensureSymlink(src, dest) console.log('success!') } catch (err) { console.error(err) } } example(srcPath, destPath) ``` -------------------------------- ### Write JSON with Promises Source: https://github.com/jprichardson/node-fs-extra/blob/master/docs/writeJson.md This snippet demonstrates how to write an object to a JSON file using Promises, allowing for cleaner asynchronous error handling with .then() and .catch(). ```javascript // With Promises: fs.writeJson('./package.json', {name: 'fs-extra'}) .then(() => { console.log('success!') }) .catch(err => { console.error(err) }) ``` -------------------------------- ### ensureLinkSync(srcPath, destPath) Source: https://github.com/jprichardson/node-fs-extra/blob/master/docs/ensureLink-sync.md Ensures that the link exists. If the directory structure does not exist, it is created. This is a synchronous method. ```APIDOC ## ensureLinkSync(srcPath, destPath) ### Description Ensures that the link exists. If the directory structure does not exist, it is created. ### Method `ensureLinkSync` (synchronous) ### Parameters #### Path Parameters - **srcPath** (String) - Description of the source path for the link. - **destPath** (String) - Description of the destination path for the link. ### Example: ```js const fs = require('fs-extra') const srcPath = '/tmp/file.txt' const destPath = '/tmp/this/path/does/not/exist/file.txt' fs.ensureLinkSync(srcPath, destPath) // link has now been created, including the directory it is to be placed in ``` ``` -------------------------------- ### ensureDir(dir[, options][, callback]) Source: https://github.com/jprichardson/node-fs-extra/blob/master/docs/ensureDir.md Ensures that the directory exists. If the directory structure does not exist, it is created. This function can be used with callbacks or Promises. ```APIDOC ## ensureDir(dir[, options][, callback]) ### Description Ensures that the directory exists. If the directory structure does not exist, it is created recursively. ### Method Asynchronous (Callback or Promise) ### Parameters #### Path Parameters - **dir** (string) - Required - The path to the directory to ensure exists. #### Options - **options** (integer | object) - Optional - Specifies the mode for directory creation. - If an integer, it is treated as the `mode`. - If an object, it should have a `mode` property (integer). #### Callback - **callback** (function) - Optional - A function to be called upon completion. - **err** (Error) - An error object if an error occurred, otherwise null. ### Request Example (Callback) ```js const fs = require('fs-extra') const dir = '/tmp/this/path/does/not/exist' fs.ensureDir(dir, err => { if (err) return console.error(err) console.log('Directory created successfully!') }) ``` ### Request Example (Callback with Mode Integer) ```js const fs = require('fs-extra') const dir = '/tmp/this/path/does/not/exist' const desiredMode = 0o2775 fs.ensureDir(dir, desiredMode, err => { if (err) return console.error(err) console.log('Directory created successfully with mode 0o2775!') }) ``` ### Request Example (Promise) ```js const fs = require('fs-extra') const dir = '/tmp/this/path/does/not/exist' fs.ensureDir(dir) .then(() => console.log('Directory created successfully!')) .catch(err => console.error(err)) ``` ### Request Example (Promise with Mode Integer) ```js const fs = require('fs-extra') const dir = '/tmp/this/path/does/not/exist' const desiredMode = 0o2775 fs.ensureDir(dir, desiredMode) .then(() => console.log('Directory created successfully with mode 0o2775!')) .catch(err => console.error(err)) ``` ### Request Example (Async/Await) ```js const fs = require('fs-extra') const dir = '/tmp/this/path/does/not/exist' async function createDir (directory) { try { await fs.ensureDir(directory) console.log('Directory created successfully!') } catch (err) { console.error(err) } } createDir(dir) ``` ### Request Example (Async/Await with Options Object) ```js const fs = require('fs-extra') const dir = '/tmp/this/path/does/not/exist' const options = { mode: 0o2775 } async function createDirWithOptions (directory) { try { await fs.ensureDir(directory, options) console.log('Directory created successfully with options!') } catch (err) { console.error(err) } } createDirWithOptions(dir) ``` ### Response #### Success Response - **No explicit return value on success when using callback.** - **Promise resolves with `undefined` on success.** #### Error Handling - **Callback:** The `err` argument in the callback will contain an error object if the directory creation fails. - **Promise:** The Promise will be rejected with an error object if the directory creation fails. ```