Node 常用模块之 fs-extra
fs-extra模块是系统fs模块的扩展,提供了更多便利的 API,并继承了fs模块的 API。 项目地址:https://github.com/jprichardson/node-fs-extra
# 安装
npm install fs-extra --save
# 使用
const fs = require('fs') // this is no longer necessary
const fse = require('fs-extra')
2
# 示例
const fs = require('fs-extra')
// Async with promises:
fs.copy('/tmp/myfile', '/tmp/mynewfile')
.then(() => console.log('success!'))
.catch(err => console.error(err))
// Async with callbacks:
fs.copy('/tmp/myfile', '/tmp/mynewfile', err => {
if (err) return console.error(err)
console.log('success!')
})
// Sync:
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()
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# API
# copy(src, dest[, options][, callback])
复制文件或目录。目录可以包含内容。
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()
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
使用过滤函数
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
3
4
5
6
7
8
9
10
11
# copySync(src, dest[, options])
const fs = require('fs-extra')
// copy file
fs.copySync('/tmp/myfile', '/tmp/mynewfile')
// copy directory, even if it has subdirectories or files
fs.copySync('/tmp/mydir', '/tmp/mynewdir')
2
3
4
5
6
7
使用过滤函数
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 })
2
3
4
5
6
7
8
# emptyDir(dir[, callback])
确保目录为空。如果目录不为空,则删除目录内容。如果目录不存在,则创建它。不会删除目录本身。别名: emptydir()
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()
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# emptyDirSync(dir[, callback])
const fs = require('fs-extra')
// assume this directory has a lot of files and folders
fs.emptyDirSync('/tmp/some/dir')
2
3
4
# ensureDir(dir[,options][,callback])
确保目录存在。如果目录结构不存在,则创建它。别名:mkdirs()
, mkdirp()
const fs = require('fs-extra')
const dir = '/tmp/this/path/does/not/exist'
const desiredMode = 0o2775
const options = {
mode: 0o2775
}
// 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 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
})
// With Promises:
fs.ensureDir(dir)
.then(() => {
console.log('success!')
})
.catch(err => {
console.error(err)
})
// With Promises and a mode integer:
fs.ensureDir(dir, desiredMode)
.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)
// 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)
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# ensureDirSync(dir[,options])
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 现在已经创建,包括它将被放置在的目录,权限为0o2775
fs.ensureDirSync(dir, options)
// dir has now been created, including the directory it is to be placed in with permission 0o2775
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# ensureLink(srcPath, destPath[, callback])
确保链接存在。如果目录结构不存在,则创建它。别名: createLink()
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
})
// With Promises:
fs.ensureLink(srcPath, destPath)
.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, destPath)
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# ensureLinkSync(srcPath, destPath)
别名:createLinkSync()
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
2
3
4
5
6
# ensureFile(file[, callback])
确保文件存在。如果请求创建的文件位于不存在的目录中,则会创建这些目录。如果文件已经存在,则不修改。别名:createFile()
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)
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# ensureFileSync(file)
别名: createFileSync()
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
2
3
4
5
# ensureSymlink(srcPath, destPath[, type][, callback])
确保符号链接存在。如果目录结构不存在,则创建它。别名:createSymlink()
const fs = require('fs-extra')
const srcPath = '/tmp/file.txt'
const destPath = '/tmp/this/path/does/not/exist/file.txt'
// With a callback:
fs.ensureSymlink(srcPath, destPath, err => {
console.log(err) // => null
// symlink has now been created, including the directory it is to be placed in
})
// With Promises:
fs.ensureSymlink(srcPath, destPath)
.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, destPath)
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# ensureSymlinkSync(srcPath, destPath[, type])
别名:createSymlinkSync()
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
2
3
4
5
6
# move(src, dest[, options][, callback])
移动文件或目录,甚至跨设备移动。
const fs = require('fs-extra')
const src = '/tmp/file.txt'
const dest = '/tmp/this/path/does/not/exist/file.txt'
// With a callback:
fs.move(src, dest, err => {
if (err) return console.error(err)
console.log('success!')
})
// With Promises:
fs.move(src, dest)
.then(() => {
console.log('success!')
})
.catch(err => {
console.error(err)
})
// 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)
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
Using overwrite
option
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!')
})
2
3
4
5
6
# moveSync(src, dest[, options])
const fs = require('fs-extra')
fs.moveSync('/tmp/somefile', '/tmp/does/not/exist/yet/somefile')
2
3
Using overwrite
option
const fs = require('fs-extra')
fs.moveSync('/tmp/somedir', '/tmp/may/already/exist/somedir', { overwrite: true })
2
3
# outputFile(file, data[, options][, callback])
几乎与writeFile
相同(即它覆盖 (opens new window)),但如果父目录不存在,则会创建它file
必须是文件路径(不允许使用缓冲区或文件描述符)。
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)
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# outputFileSync(file, data[, options])
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!
2
3
4
5
6
7
# outputJson(file, object[, options][, callback])
只是如果目录不存在,则会创建它。别名: outputJSON()
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)
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# outputJsonSync(file, object[, options])
别名:outputJSONSync()
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
2
3
4
5
6
7
# pathExists(file[, callback])
通过检查文件系统来测试给定的路径是否存在。像fs.exists
(opens new window),但具有普通回调签名(err,exists)。在引擎盖下使用fs.access
。
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)
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# pathExistsSync(file)
[fs.existsSync()
]的别名(https://nodejs.org/api/fs.html#fs_fs_existssync_path),为与[pathExists()
](pathExists.md)保持一致而创建。
# readJson(file[, options][, callback])
读取JSON文件,然后将其解析为对象。别名:readJSON()
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()
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
readJson()
可以将throws
选项设置为false
,如果JSON
无效,它将不会抛出。例子:
const fs = require('fs-extra')
const file = '/tmp/some-invalid.json'
const data = '{not valid JSON'
fs.writeFileSync(file, data)
// With a callback:
fs.readJson(file, { throws: false }, (err, obj) => {
if (err) console.error(err)
console.log(obj) // => null
})
// Wtih Promises:
fs.readJson(file, { throws: false })
.then(obj => {
console.log(obj) // => null
})
.catch(err => {
console.error(err) // Not called
})
// With async/await:
async function example (f) {
const obj = await fs.readJson(f, { throws: false })
console.log(obj) // => null
}
example(file)
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# readJsonSync(file[, options])
别名: readJSONSync()
const fs = require('fs-extra')
const packageObj = fs.readJsonSync('./package.json')
console.log(packageObj.version) // => 2.0.0
2
3
4
readJsonSync()
可以将throws
选项设置为false
,如果JSON
无效,它将不会抛出。例子:
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
2
3
4
5
6
7
8
# remove(path[, callback])
删除文件或目录。目录可以包含内容。如果路径不存在,则静默不执行任何操作。
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()
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# removeSync(path)
const fs = require('fs-extra')
// remove file
fs.removeSync('/tmp/myfile')
fs.removeSync('/home/jprichardson') // I just deleted my entire HOME directory.
2
3
4
5
6
# writeJson(file, object[, options][, callback])
将对象写入JSON文件。别名:writeJSON()
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()
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# writeJsonSync(file, object[, options])
别名: writeJSONSync()
const fs = require('fs-extra')
fs.writeJsonSync('./package.json', {name: 'fs-extra'})
2
3
# fs.read() 和 fs.write()
fs.read()
(opens new window),fs.write()
(opens new window),&fs.writev()
(opens new window)与其他“fs”方法不同的是,它们的回调是用3个参数而不是通常的2个参数来调用的。
如果您将它们与回调一起使用,它们的行为将一如既往。但是,它们的promise用法有点不同fs extra
promisify这些方法,如util.promisify()
(opens new window)(仅在节点8+)中可用。
下面是promise用法的示例:
fs.read()
// With Promises:
fs.read(fd, buffer, offset, length, position)
.then(results => {
console.log(results)
// { bytesRead: 20, buffer: <Buffer 0f 34 5d ...> }
})
// With async/await:
async function example () {
const { bytesRead, buffer } = await fs.read(fd, Buffer.alloc(length), offset, length, position)
}
2
3
4
5
6
7
8
9
10
11
fs.write()
// With Promises:
fs.write(fd, buffer, offset, length, position)
.then(results => {
console.log(results)
// { bytesWritten: 20, buffer: <Buffer 0f 34 5d ...> }
})
// With async/await:
async function example () {
const { bytesWritten, buffer } = await fs.write(fd, Buffer.alloc(length), offset, length, position)
}
2
3
4
5
6
7
8
9
10
11
fs.writev()
// With async/await:
async function example () {
const { bytesWritten, buffers } = await fs.writev(fd, buffers, position)
}
2
3
4
- 02
- Node与GLIBC_2.27不兼容解决方案08-19
- 03
- Git清空本地文件跟踪缓存08-13