Fs-extra is an extension of FS that provides many convenient apis, inherits all fs methods and adds promise support for FS methods.
It should be a replacement for FS.
Why is that?
I am tired of including MKDIRP, RIMRAF and NCP in most of my projects.
What problem was solved
Before using it, it is important to understand what problems third-party libraries solve for existing libraries and not to use it just for the sake of using it.
Fs-extra emulates commands like those in Linux:
root$ rm -rf /
root$ mv tmpDir tmpNewDir
root$ mkdir -p one/two
root$ cp -r tmp tmpNew
...
Copy the code
It’s convenient, isn’t it? That’s why I fell in love with it!
The installation
npm install fs-extra -S
Copy the code
usage
Fs-extra should always be used instead of fs. All FS methods are attached to fs-extra. If FS does not pass a callback, all methods will return a promise.
I don’t need this anymore
const fs = require('fs');
Copy the code
You can do that now
const fs = require('fs-extra');
Copy the code
If you want to make it clear that you are using FS-extra, you can change the FS identifier to FSE
const fse = require('fs-extra');
Copy the code
You can keep both, but it’s redundant because Fs-extra inherits from FS
const fs = require('fs');
const fse = require('fs-extra');
Copy the code
Sync vs Async vs Async/Await
Most methods are asynchronous by default, and all asynchronous methods return a Promise if no callback is passed.
A case in point:
const fs = require('fs-extra') // Asynchronous method, return promise fs.copy('/tmp/myfile'.'/tmp/mynewfile')
.then(() => console.log('success! ').catch(err => console.error(err))'/tmp/myfile'.'/tmp/mynewfile', err => {
if (err) return console.error(err)
console.log('success! 'Try {fs.copysync () {fs.copysync () {fs.copysync () {fs.copysync () {fs.copysync ();'/tmp/myfile'.'/tmp/mynewfile')
console.log('success! ')
} catch (err) {
console.error(err)
}
// Async/Await:
async function copyFiles () {
try {
await fs.copy('/tmp/myfile'.'/tmp/mynewfile')
console.log('success! ')
} catch (err) {
console.error(err)
}
}
copyFiles()
Copy the code
API Methods
All of the following methods are fs-extra extension methods
Async/asynchronous
- copy
- EmptyDir (alias: emptyDir)
- ensureFile
- EnsureDir (alias: mkdirp, mkdirs)
- ensureLink
- ensureSymlink
- mkdirp
- mkdirs
- move
- outputFile
- OutputJson (alias: outputJson)
- pathExists
- ReadJson (alias: readJson)
- remove
- WriteJson (alias: writeJson)
The Sync/synchronization
- copySync
- emptyDirSync
- ensureFileSync
- ensureDirSync
- ensureLinkSync
- ensureSymlinkSync
- mkdirpSync
- mkdirsSync
- moveSync
- outputFileSync
- outputJsonSync
- pathExistsSync
- readJsonSync
- removeSync
- writeJsonSync
Copy (SRC: string, dest: string, [options: object, callback: func])
Copy a file or directory that can contain content, similar to cp -r
- SRC Note that if SRC is a directory, it copies everything in that directory, not the entire directory itself
- Dest Note that if SRC is a file, dest cannot be a directory
- options
- Overwrite: overwrites existing files or directories. The default value is true. Note that if this is set to false and the target exists, the replication operation will fail without warning. Use the errorOnExist option to change this behavior.
- ErrorOnExist: An error is thrown when overwrite is false and the target exists. The default is false.
- Dereference: Dereference symlinks, false by default.
- PreserveTimestamps: If true, the last modification and access times to the original source files are set. If false, the timestamp behavior depends on the operating system. The default is false.
- Filter: indicates the function of filtering copied files. Returns true to include, false to exclude. You can also return a Promise resolved to true or false (or pass in an async function).
- Callback callback function
Example:
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
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
// With Promises:
fs.copy('/tmp/myfile'.'/tmp/mynewfile')
.then(() => {
console.log('success! ')
})
.catch(err => {
console.error(err)
})
// With async/await:
async function example () {
try {
await fs.copy('/tmp/myfile'.'/tmp/mynewfile')
console.log('success! ')
} catch (err) {
console.error(err)
}
}
example()
Copy the code
Using filter functions
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! ')})Copy the code
2, emptyDir(dir: string, [callback: function])
Make sure the directory is empty. If the directory is not empty, the directory is deleted. If the directory does not exist, it is created. The directory itself is not deleted.
Alias: emptydir ()
- Dir Destination path
- Callback callback method
Example:
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! ')
})
// With Promises:
fs.emptyDir('/tmp/some/dir')
.then(() => {
console.log('success! ')
})
.catch(err => {
console.error(err)
})
// With async/await:
async function example () {
try {
await fs.emptyDir('/tmp/some/dir')
console.log('success! ')
} catch (err) {
console.error(err)
}
}
example()
Copy the code
3, ensureFile(file: string, [callback: func])
Make sure the file exists. If the requested file is in a directory that does not exist, these directories will be created. If the file already exists, do not modify it.
Alias: createFile ()
- File Destination path
- Callback callback method
Example:
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 the code
4, ensureDir(dir: string, [callback: func])
If the directory structure does not exist, create it; if the directory exists, do not create it, similar to mkdir -p.
Aliases: mkdirs(), mkdirp()
- Dir Destination path
- Callback callback method
Example:
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
})
// With Promises:
fs.ensureDir(dir)
.then(() => {
console.log('success! ')
})
.catch(err => {
console.error(err)
})
// With async/await:
async function example (directory) {
try {
await fs.ensureDir(directory)
console.log('success! ')
} catch (err) {
console.error(err)
}
}
example(dir)
Copy the code
5, ensureLink(srcPath: string, dstPath: string, [callback: func])
Make sure the link exists. If the directory structure does not exist, create it.
- Srcpath source path
- Dstpath Destination path
- Callback callback method
example
const fs = require('fs-extra')
const srcpath = '/tmp/file.txt'
const dstpath = '/tmp/this/path/does/not/exist/file.txt'
// With a callback:
fs.ensureLink(srcpath, dstpath, err => {
console.log(err) // => null
// link has now been created, including the directory it is to be placed in
})
// With Promises:
fs.ensureLink(srcpath, dstpath)
.then(() => {
console.log('success! ')
})
.catch(err => {
console.error(err)
})
// With async/await:
async function example (src, dest) {
try {
await fs.ensureLink(src, dest)
console.log('success! ')
} catch (err) {
console.error(err)
}
}
example(srcpath, dstpath)
Copy the code
6, ensureSymlink(srcPath: string, dstPath: string, [callback: func])
Make sure symlinks exist. If the directory structure does not exist, create it.
- Srcpath source path
- Dstpath Destination path
- Callback callback method
const fs = require('fs-extra')
const srcpath = '/tmp/file.txt'
const dstpath = '/tmp/this/path/does/not/exist/file.txt'
// With a callback:
fs.ensureSymlink(srcpath, dstpath, err => {
console.log(err) // => null
// symlink has now been created, including the directory it is to be placed in
})
// With Promises:
fs.ensureSymlink(srcpath, dstpath)
.then(() => {
console.log('success! ')
})
.catch(err => {
console.error(err)
})
// With async/await:
async function example (src, dest) {
try {
await fs.ensureSymlink(src, dest)
console.log('success! ')
} catch (err) {
console.error(err)
}
}
example(srcpath, dstpath)
Copy the code
7, move(SRC: string, dest: string, [options: object, callback: func])
Move files or directories, even across devices. Similar to the mv
- Srcpath source path
- Dstpath Destination path
- options
- Overwrite: overwrites existing files or directories. The default value is false.
- Callback callback method
Example:
const fs = require('fs-extra')
const srcpath = '/tmp/file.txt'
const dstpath = '/tmp/this/path/does/not/exist/file.txt'
// With a callback:
fs.move(srcpath, dstpath, err => {
if (err) return console.error(err)
console.log('success! ')
})
// With Promises:
fs.move(srcpath, dstpath, {
overwrite: true
})
.then(() => {
console.log('success! ')
})
.catch(err => {
console.error(err)
})
// With async/await:
async function example (src, dest) {
try {
await fs.move(srcpath, dstpath)
console.log('success! ')
} catch (err) {
console.error(err)
}
}
example(srcpath, dstpath)
Copy the code
8, outputFile (file: stirng, data: string | Buffer | Uint8Array, [options: string | object, the callback: func])
Almost the same as writeFile (that is, it overrides), except that if the parent directory does not exist, it is created. File must be a file path (buffers or file descriptors are not allowed).
- File Indicates the file path
- Data Data written to a file
- options
- Utf8 encoding | defaults to ‘ ‘
- Mode The default value is 0o666
- Flag See supported file system flag. The default value is ‘w’.
- Callback callback method
Example:
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)
Copy the code
9, outputJson(File: string, object: object, [options: object, callback: func])
Almost the same as writeJson, except that if the directory does not exist, it is created.
Alias: outputJSON ()
- File Indicates the file path
- Object The JSON object to which the file is written
- options
- Utf8 encoding | defaults to ‘ ‘
- Mode The default value is 0o666
- Flag See supported file system flag. The default value is ‘w’.
- Spaces < number | string > indentation on the number of Spaces; Or a string for indentation (i.e. passing the ‘\t’ tag indent)
- EOL Sets the EOL character. The default is \n.
- replacer JSON replacer
- Callback callback method
Example:
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
})
})
// With Promises:
fs.outputJson(file, {name: 'JP'})
.then(() => fs.readJson(file))
.then(data => {
console.log(data.name) // => JP
})
.catch(err => {
console.error(err)
})
// 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)
Copy the code
10, pathExists(file: string [, callback: func])
Tests the existence of a given path by examining the file system. Similar to the fs. The exists
- File File path
- Callback callback function
Example:
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)
Copy the code
ReadJson (file: string, [options: object, callback: func])
Read the JSON file and parse it into an object
Alias: readJSON ()
- File Path of the JSON file
- options
- Throws Err if false and JSON is invalid, it will not throw err. The default is true
- Callback callback function
Example:
const fs = require('fs-extra')
// With a callback:
fs.readJson('./package.json', (err, packageObj) => {
if (err) console.error(err)
console.log(packageObj.version) // => 0.1.3
})
// With Promises:
fs.readJson('./package.json').then(packageObj => {console.log(packageobj.version) // => 0.1.3}).catch(err => {console.error(err)}) // With async/await: asyncfunction example () {
try {
const packageObj = await fs.readJson('./package.json') console.log(packageobj.version) // => 0.1.3} Catch (err) {console.error(err)}} example()Copy the code
Add (path: string, [callback: func]);
Delete a file or directory. This directory can contain content, similar to rm -rf
- Path Target path
- Callback callback function
Example:
const fs = require('fs-extra')
// remove file
// With a callback:
fs.remove('/tmp/myfile', err => {
if (err) return console.error(err)
console.log('success! ')
})
fs.remove('/home/jprichardson', err => {
if (err) return console.error(err)
console.log('success! ') // I just deleted my entire HOME directory.
})
// With Promises:
fs.remove('/tmp/myfile')
.then(() => {
console.log('success! ')
})
.catch(err => {
console.error(err)
})
// With async/await:
async function example (src, dest) {
try {
await fs.remove('/tmp/myfile')
console.log('success! ')
} catch (err) {
console.error(err)
}
}
example()
Copy the code
13, writeJson(File, object, [options, callback])
Writing an object to a JSON file is almost identical to outputJson, except that the directory must exist.
Alias: writeJSON ()
- File Indicates the file path
- Object The JSON object to which the file is written
- options
- Utf8 encoding | defaults to ‘ ‘
- Mode The default value is 0o666
- Flag See supported file system flag. The default value is ‘w’.
- Spaces < number | string > indentation on the number of Spaces; Or a string for indentation (i.e. passing the ‘\t’ tag indent)
- EOL Sets the EOL character. The default is \n.
- replacer JSON replacer
- Callback callback method
Example:
const fs = require('fs-extra')
// With a callback:
fs.writeJson('./package.json', {name: 'fs-extra'}, err => {
if (err) return console.error(err)
console.log('success! ')
})
// With Promises:
fs.writeJson('./package.json', {name: 'fs-extra'})
.then(() => {
console.log('success! ')
})
.catch(err => {
console.error(err)
})
// With async/await:
async function example () {
try {
await fs.writeJson('./package.json', {name: 'fs-extra'})
console.log('success! ')
} catch (err) {
console.error(err)
}
}
example()
Copy the code
Write in the last
There is no doubt that FS-Extra is a good choice in production environment, but if you want to play the black technology, you should know more about FS module, after all, it is the boss.
The original link