NoteZ_技术博客 NoteZ_技术博客
🏠 首页
  • 📚 Web技术
  • 📋 Npm笔记
  • 📑 Markdown
  • 📄 Git笔记
  • 📝 Nginx文档
  • 📓 Linux文档
  • 📖 技术文档
  • 📜 其他文档
  • 🧊 NodeJs
  • 🎡 Express
  • 🔥 Rust
  • 🎉 Koa2
  • 🍃 MongoDB
  • 🐬 MySql
  • 🥦 Oracle
  • 🍁 Python
  • 🍄 JavaScript
  • 🌰 CSS
  • 🧄 HTML
  • 🥑 Canvas
  • 🌽 Nuxt
  • 🍆 React
  • 🥜 Vue
  • 🧅 TypeScript
  • 🌶️ AI
  • 📘 分类
  • 📗 标签
  • 📙 归档
⚜️ 在线编辑 (opens new window)
  • 📁 站点收藏
  • 📦 前端组件库
  • 📊 数据可视化
  • 🌈 开源插件
  • 🎗️ 关于我
  • 🔗 友情链接
GitHub (opens new window)

NoteZ_技术博客

前端界的小学生
🏠 首页
  • 📚 Web技术
  • 📋 Npm笔记
  • 📑 Markdown
  • 📄 Git笔记
  • 📝 Nginx文档
  • 📓 Linux文档
  • 📖 技术文档
  • 📜 其他文档
  • 🧊 NodeJs
  • 🎡 Express
  • 🔥 Rust
  • 🎉 Koa2
  • 🍃 MongoDB
  • 🐬 MySql
  • 🥦 Oracle
  • 🍁 Python
  • 🍄 JavaScript
  • 🌰 CSS
  • 🧄 HTML
  • 🥑 Canvas
  • 🌽 Nuxt
  • 🍆 React
  • 🥜 Vue
  • 🧅 TypeScript
  • 🌶️ AI
  • 📘 分类
  • 📗 标签
  • 📙 归档
⚜️ 在线编辑 (opens new window)
  • 📁 站点收藏
  • 📦 前端组件库
  • 📊 数据可视化
  • 🌈 开源插件
  • 🎗️ 关于我
  • 🔗 友情链接
GitHub (opens new window)
  • Express

  • Koa2

  • MongoDB

  • MySql

  • NodeJs

    • 2021 年值得使用的 Node.js 框架
    • CentOS 7上安装 Node.js 的 4 种方法
    • Linux 下安装 NodeJs 以及版本的升级和降级
    • node 中 path 模块 normalize 函数格式化路径
    • Node 中 使用 fs.stat() 读取文件状态
    • Node 中使用 compressing 压缩文件夹为 zip 文件
    • Node 中的实现 EventEmitter (event)方法
    • Node 代理 Demo 示例
    • node 判断文件或文件夹是否存在
    • node 复制文件的五种方式
    • Node 常用模块之 fs-extra
      • 安装
      • 使用
      • 示例
      • API
        • copy(src, dest[, options][, callback])
        • copySync(src, dest[, options])
        • emptyDir(dir[, callback])
        • emptyDirSync(dir[, callback])
        • ensureDir(dir[,options][,callback])
        • ensureDirSync(dir[,options])
        • ensureLink(srcPath, destPath[, callback])
        • ensureLinkSync(srcPath, destPath)
        • ensureFile(file[, callback])
        • ensureFileSync(file)
        • ensureSymlink(srcPath, destPath[, type][, callback])
        • ensureSymlinkSync(srcPath, destPath[, type])
        • move(src, dest[, options][, callback])
        • moveSync(src, dest[, options])
        • outputFile(file, data[, options][, callback])
        • outputFileSync(file, data[, options])
        • outputJson(file, object[, options][, callback])
        • outputJsonSync(file, object[, options])
        • pathExists(file[, callback])
        • pathExistsSync(file)
        • readJson(file[, options][, callback])
        • readJsonSync(file[, options])
        • remove(path[, callback])
        • removeSync(path)
        • writeJson(file, object[, options][, callback])
        • writeJsonSync(file, object[, options])
        • fs.read() 和 fs.write()
    • node 操作 mongodb 数据库备份与还原-示例代码
    • node 获取请求 ip
    • Node 读取和写入 json 文件
    • Node 递归或 mkdirp 创建多层目录
    • Node 遍历目录输出树形文件目录结构
    • Node(publish-sftp)命令上传本地文件到服务器
    • Node.js 中使用 compressing 实现zip文件的解压,解决文件名中文乱码
    • node.js 读取文件目录下的所有读取文件目录
    • Node.js把前台传来的 base64 码转成图片
    • nodeJs + vueJs 实现大文件分片上传
    • NodeJs 使用 jszip 或者 zip-dir 压缩文件夹(zip)
    • NodeJs 利用 jszip 压缩文件、文件夹,以及解压压缩文件中的文件
    • NodeJs 实现简单 WebSocket 即时通讯
    • NodeJs 框架 Express 的两种使用方式
    • NodeJs与Nginx获取客户端真实IP方法
    • NodeJs之大文件断点下载
    • NodeJS使用node-fetch下载文件并显示下载进度
    • NodeJs将图片进行压缩生成缩略图
    • nodejs递归读取所有文件
    • Node中复制文件的四种方法总结
    • node中的读取流createReadStream、写入流createWriteStream和管道流pipe
    • Node开发笔记
    • Node递归创建多层目录并写入文件
    • Node递归创建文件夹
    • PM2配置文件的使用、管理多个Node.js项目
    • 使用 koa-generator 快速搭建 Koa2 项目
    • 使用 pm2 部署 nodejs 项目
    • 使用 supervisor 自动重启 NodeJs 提高开发效率
    • 使用node反向代理解决跨域问题
    • 使用node实现保存(上传)图片的功能
    • 使用Node搭建超高压缩比的图片(webp)压缩服务
    • 前端部署从静态到node再到负载均衡
    • 在 NodeJs 中使用 compressing 压缩和解压缩文件或文件夹
    • 在 nodejs 执行 shell 指令
    • 基于 Node 生成 vue 模板文件
    • 如何使用 Nodejs 备份 MongoDB 数据
    • 如何使用NodeJs实现base64和png文件相互转换
    • 如何在 Linux 服务器上使用 Nodejs 连接远程 Oracle 数据库
    • 混淆、编译 Node.js 源代码的几种方法
    • Node.js包之archiver压缩打包文件或目录为zip格式
    • node.js获取目录内所有文件大小总和
    • NodeJs 中使用 resize-img 制作缩略图
    • nodeJS中的http模块基本介绍
    • nodejs图片处理工具gm用法
    • node使用ffmpeg将swf转mp4 截取mp4视频第一帧为jpg图片
    • 如何在Node.js中执行shell命令
    • NodeJs 中复制(拷贝)文件或文件夹的多种方式
    • 在 NodeJs 中使用 archiver 压缩超大文件夹
    • Node.js 中使用 ssh2-sftp-client 上传文件并实时获取速率大小和进度
    • Node.js 中使用 ssh2-sftp-client 上传文件到服务器示例
    • node 使用 ssh2-sftp-client 实现 FTP 的文件上传和下载功能
    • ssh2-sftp-client 上传文件夹时获取上传速度和文件夹大小
    • 基于 node 使用 UDP 上传文件示例
    • 利用Node.js监控文件变化并使用sftp上传到服务器
    • 利用 Node 监控文件夹或文件夹变化可用的 npm 包汇总
    • NodeJS获取当前目录、运行文件所在目录、运行文件的上级目录
    • Node与GLIBC_2.27不兼容解决方案
  • Oracle

  • Rust

  • Python

  • 后端开发
  • NodeJs
NoteZ
2020-12-22
目录

Node 常用模块之 fs-extra

fs-extra模块是系统fs模块的扩展,提供了更多便利的 API,并继承了fs模块的 API。 项目地址:https://github.com/jprichardson/node-fs-extra

# 安装

npm install fs-extra --save
1

# 使用

const fs = require('fs') // this is no longer necessary
const fse = require('fs-extra')
1
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()
1
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()
1
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!')
})
1
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')
1
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 })
1
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()
1
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')
1
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)
1
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
1
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)
1
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
1
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)
1
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
1
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)
1
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
1
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)
1
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!')
})
1
2
3
4
5
6

# moveSync(src, dest[, options])

const fs = require('fs-extra')

fs.moveSync('/tmp/somefile', '/tmp/does/not/exist/yet/somefile')
1
2
3

Using overwrite option

const fs = require('fs-extra')

fs.moveSync('/tmp/somedir', '/tmp/may/already/exist/somedir', { overwrite: true })
1
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)
1
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!
1
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)
1
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
1
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)
1
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()
1
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)
1
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
1
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
1
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()
1
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.
1
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()
1
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'})
1
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 extrapromisify这些方法,如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)
}
1
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)
}
1
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)
}
1
2
3
4
#NodeJs
上次更新: 2024/01/30, 00:35:17
node 复制文件的五种方式
node 操作 mongodb 数据库备份与还原-示例代码

← node 复制文件的五种方式 node 操作 mongodb 数据库备份与还原-示例代码→

最近更新
01
Gitea数据备份与还原
03-10
02
Linux 中使用 rsync 同步文件目录教程
03-10
03
Linux 使用 rsync 互相传输同步文件的简单步骤
03-08
更多文章>
Theme by Vdoing | Copyright © 2019-2025 NoteZ,All rights reserved | 冀ICP备2021027292号-1
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式