What was solved
Before using it, it is important to understand what problems the third-party library solves for existing libraries, and not to use it just for the sake of using it.
fs-extra emulates commands similar to those used in Linux:
root$ rm -rf /
root$ mv tmpDir tmpNewDir
root$ mkdir -p one/two
root$ cp -r tmp tmpNew
...
It’s handy isn’t it? That’s what made me fall in love with it!
npm install fs-extra -S
Should always fs-extra be used instead of fs, all fs methods are attached to fs-extra, and fs will return promise for all methods if no callback is passed.
Don’t need this anymore.
const fs = require('fs');
You can do this now.
const fs = require('fs-extra');
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');
You can keep both for use, but it’s redundant because fs-extra inherits fs
const fs = require('fs');
const fse = require('fs-extra');
Sync vs Async vs Async/Await
Most methods are asynchronous by default, and all asynchronous methods will return a promise if no callback is passed.
A typical example:
const fs = require('fs-extra')
fs.copy('/tmp/myfile', '/tmp/mynewfile')
.then(() => console.log('success!'))
.catch(err => console.error(err))
fs.copy('/tmp/myfile', '/tmp/mynewfile', err => {
if (err) return console.error(err)
console.log('success!')
})
try {
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()
API Methods
All of the following methods are fs-extra extension methods
Async
- copy
- emptyDir (alias: emptyydir)
- ensureFile
- ensureDir (mkdirp、mkdirs)
- ensureLink
- ensureSymlink
- mkdirp
- mkdirs
- move
- outputFile
- outputJson (outputJSON)
- pathExists
- readJson (readJSON)
- remove
- writeJson (writeJSON)
Sync/Synchronization
- copySync
- emptyDirSync
- ensureFileSync
- ensureDirSync
- ensureLinkSync
- ensureSymlinkSync
- mkdirpSync
- mkdirsSync
- moveSync
- outputFileSync
- outputJsonSync
- pathExistsSync
- readJsonSync
- removeSync
- writeJsonSync
1、copy(src: string, dest: string, [options: object, callback: func])
Copy a file or directory, directories can contain content, similar to cp -r
src Note that if src is a directory, it will copy everything in that directory, not the entire directory itself.
dest Note that if src is a file, dest cannot be a directory.- options
overwrite : overwrite an existing file or directory, defaults to true. note that if this is set to false and the target exists, the copy operation will fail without prompting. Use this errorOnExist option to change this behavior.
errorOnExist : Throw an error when overwrite is false and the target exists. Default is false.- dereference : dereference symlinks,false。
preserveTimestamps : If true, sets the last modification and access time to the original source file. If false, timestamp behavior depends on the operating system. The default is false.
filter : Filtering of copied files. Returns true to include, false to exclude. Can also return Promise parsed to true or false (or pass in an async function).
- callback function
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()
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!')
})
2、emptyDir(dir: string, [callback: function])
Make sure the directory is empty. If the directory is not empty, delete the contents of the directory. If the directory does not exist, the directory is created. The directory itself is not deleted.
emptydir()
- dir Destination path
- callback method
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()
3、ensureFile(file: string, [callback: func])
Ensure that the file exists. If the file requested to be created is located in directories that do not exist, those directories are created. If the file already exists, it is not modified.
createFile()
- file Destination path
- callback method
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)
4、ensureDir(dir: string, [callback: func])
If the directory structure does not exist, it is created, and if the directory exists, it is not created, similar to mkdir -p.
mkdirs(), mkdirp()
- dir Destination path
- callback method
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)
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 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.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)
6、ensureSymlink(srcpath: string, dstpath: string, [callback: func])
Make sure the symbolic link exists. If the directory structure does not exist, create it.
- srcpath source path
- dstpath Destination path
- 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)
7、move(src: string, dest: string, [options: object, callback: func])
Move files or directories, even across devices. Similar to mv
- srcpath source path
- dstpath Destination path
- options
overwrite : overwrite an existing file or directory, default is false.
- 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.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)
8、outputFile(file: stirng, data: string|Buffer|Uint8Array, [options: string|object, callback: func])
Almost identical to writeFile (i.e., it overwrites), except that the parent directory is created if it does not exist. file must be a file path (buffers or file descriptors are not allowed).
- file Write file path
- data Data written to the file
- options
- encoding | ‘utf8’
- mode defaults to 0o666
flag See Supported file system flags, defaults to ‘w’.
- callback method
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)
9、outputJson(file: string, object: object, [options: object, callback: func])
Almost the same writeJson, except that if the catalog doesn’t exist, it’s created.
outputJSON()
- file Write file path
- object A JSON object that writes to a file.
- options
- encoding | ‘utf8’
- mode defaults to 0o666
flag See Supported file system flags, defaults to ‘w’.
spaces <number|string> number of spaces to indent; or string to indent (i.e. pass ‘\t’ tag indent)- EOL Sets the EOL character. The default is \n.
- callback method
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)
10、pathExists(file: string [, callback: func])
Tests if a given path exists by checking the file system. Similar to fs.exists
- file File path
- callback function
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)
11、readJson(file: string, [options: object, callback: func])
Reads a JSON file and parses it into an object
readJSON()
- file JSON file path
- options
throws If false and the JSON is invalid, it will not throw err, default true.
- callback function
例子:
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:
async function example () {
try {
const packageObj = await fs.readJson('./package.json')
console.log(packageObj.version) // => 0.1.3
} catch (err) {
console.error(err)
}
}
example()
12、remove(path: string, [callback: func])
Delete a file or directory. The directory can contain content, similar to rm -rf
- path Target path
- callback function
例子:
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()
13、writeJson(file, object, [options, callback])
Writing objects to a JSON file is almost identical to outputJson, except that you have to make sure the directory exists.
writeJSON()
- file Write file path
- object A JSON object that writes to a file.
- options
- encoding | ‘utf8’
- mode defaults to 0o666
flag See Supported file system flags, defaults to ‘w’.
spaces <number|string> number of spaces to indent; or string to indent (i.e. pass ‘\t’ tag indent)- EOL Sets the EOL character. The default is \n.
- callback method
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()