fs-extra是fs的一个扩展,提供了非常多的便利API,并且继承了fs所有方法和为fs方法添加了promise的支持。

它应该是 fs 的替代品。

为什么?

我厌倦了包括mkdirp,rimraf以及ncp在我的大部分项目中。

解决了什么问题

使用前,必须了解第三方库给现有库解决了哪些问题,不要为了使用而使用。

fs-extra模拟了类似如Linux下的命令:

root$ rm -rf /
root$ mv tmpDir tmpNewDir
root$ mkdir -p one/two
root$ cp -r tmp tmpNew
...
复制代码

这很方便不是吗?这才让我深深地爱上了它!

安装

npm install fs-extra -S
复制代码

用法

应该总是fs-extra代替fs使用,所有fs方法都附在fs-extra,fs如果未传递回调,则所有方法都将返回promise。

不再需要这个

const fs = require('fs');
复制代码

你现在可以这样做

const fs = require('fs-extra');
复制代码

如果你希望明确表示你在使用fs-extra,可以将fs标识符改为fse

const fse = require('fs-extra');
复制代码

你可以保留两者使用,但它是多余的,因为 fs-extra 继承了fs

const fs = require('fs');
const fse = require('fs-extra');
复制代码

Sync vs Async vs Async/Await

大多数方法默认为异步,如果未传递回调,则所有异步方法将返回一个promise。

一个典型的例子:

const fs = require('fs-extra')// 异步方法,返回promise
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 catch包裹着才能捕获错误
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

下面的所有方法都是fs-extra扩展方法

Async/异步

  • copy
  • emptyDir (别名:emptydir)
  • ensureFile
  • ensureDir (别名:mkdirp、mkdirs)
  • ensureLink
  • ensureSymlink
  • mkdirp
  • mkdirs
  • move
  • outputFile
  • outputJson (别名:outputJSON)
  • pathExists
  • readJson (别名:readJSON)
  • remove
  • writeJson (别名:writeJSON)

Sync/同步

  • 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])

复制文件或目录,目录可以包含内容,类似 cp -r

  • src 请注意,如果src是目录,它将复制此目录内的所有内容,而不是整个目录本身
  • dest 请注意,如果src是文件,dest则不能是目录
  • options
    • overwrite : 覆盖现有文件或目录,默认为true。请注意,如果将此设置为false并且目标存在,则复制操作将无提示失败。使用该errorOnExist选项可更改此行为。
    • errorOnExist : 当overwrite为false和目标存在时,抛出错误。默认是false。
    • dereference : dereference symlinks,默认是false。
    • preserveTimestamps : 如果为true,将设置对原始源文件的最后修改和访问时间。如果为false,则时间戳行为取决于操作系统。默认是false。
    • filter : 过滤复制文件的功能。返回true包含,false排除。也可以返回Promise解析为true或false(或传入async函数)。
  • 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 filefs.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()
复制代码

使用过滤函数

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])

确保目录为空。如果目录不为空,则删除目录内容。如果该目录不存在,则创建该目录。目录本身不会被删除。

别名: emptydir()

  • dir 目标路径
  • callback 回调方法

例子:

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])

确保文件存在。如果请求创建的文件位于不存在的目录中,则会创建这些目录。如果该文件已存在,则不进行修改。

别名: createFile()

  • file 目标路径
  • callback 回调方法

例子:

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])

如果目录结构不存在,则创建它,如果目录存在,则不进行创建,类似mkdir -p。

别名: mkdirs(), mkdirp()

  • dir 目标路径
  • callback 回调方法

例子:

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])

确保链接存在。如果目录结构不存在,则创建它。

  • srcpath 源路径
  • dstpath 目标路径
  • callback 回调方法

例子

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])

确保符号链接存在。如果目录结构不存在,则创建它。

  • srcpath 源路径
  • dstpath 目标路径
  • callback 回调方法
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])

移动文件或目录,甚至跨设备。 类似 mv

  • srcpath 源路径
  • dstpath 目标路径
  • options
    • overwrite : 覆盖现有文件或目录,默认为false。
  • callback 回调方法

例子:

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])

几乎与writeFile(即它覆盖)相同,除了如果父目录不存在,则创建它。file必须是文件路径(不允许使用缓冲区或文件描述符)。

  • file 写入文件路径
  • data 写入文件的数据
  • options
    • encoding | 默认为 'utf8'
    • mode 默认为 0o666
    • flag 详见支持的文件系统flag, 默认为 'w'
  • callback 回调方法

例子:

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) // => nullfs.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])

几乎相同writeJson,除了如果目录不存在,它就被创建了。

别名: outputJSON()

  • file 写入文件路径
  • object 写入文件的JSON对象
  • options
    • encoding | 默认为 'utf8'
    • mode 默认为 0o666
    • flag 详见支持的文件系统flag, 默认为 'w'
    • spaces <number|string> 缩进的空格数; 或者用于缩进的字符串(即传递'\t'标签缩进)
    • EOL 设置EOL字符。默认是\n。
    • replacer JSON replacer
  • callback 回调方法

例子:

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) // => nullfs.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])

通过检查文件系统来测试给定路径是否存在。类似fs.exists

  • file 文件路径
  • callback 回调函数

例子:

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) // => nullconsole.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])

读取JSON文件,然后将其解析为对象

别名: readJSON()

  • file JSON文件路径
  • options
    • throws 如果为false并且JSON无效,它将不会抛出err, 默认true
  • callback 回调函数

例子:

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])

删除文件或目录。该目录可以包含内容, 类似 rm -rf

  • 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()
复制代码

13、writeJson(file, object, [options, callback])

将对象写入JSON文件, 几乎与outputJson相同,除了必须保证目录存在外。

别名: writeJSON()

  • file 写入文件路径
  • object 写入文件的JSON对象
  • options
    • encoding | 默认为 'utf8'
    • mode 默认为 0o666
    • flag 详见支持的文件系统flag, 默认为 'w'
    • spaces <number|string> 缩进的空格数; 或者用于缩进的字符串(即传递'\t'标签缩进)
    • EOL 设置EOL字符。默认是\n。
    • replacer JSON replacer
  • callback 回调方法

例子:

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()
复制代码

写在最后

毋庸置疑fs-extra用在生产环境绝对是不错的选择,但是想要玩转黑科技还是要多多了解fs模块,毕竟它才是老大。

原文链接

node-fs-extra模块代替fs使用相关推荐

  1. node内置模块中fs文件系统模块

    fs模块是Node.js官方提供的,用来操作文件的模块.它提高了一系列的方法和属性,用来满足用户对文件的操作需求.fs模块中,所有的方法分为同步和异步两种实现.有 sync 后缀的方法为同步方法,没有 ...

  2. JavaScript之后端Web服务器开发Node.JS基本模块学习篇

    JavaScript之后端Web服务器开发Node.JS基本模块学习篇 基本模块 fs文件系统模块 stream支持流模块 http crypto加密模块 基本模块 因为Node.js是运行在服务区端 ...

  3. 二十六、深入Node.js中的文件系统fs模块

    @Author:Runsen @Date:2020/6/8 人生最重要的不是所站的位置,而是内心所朝的方向.只要我在每篇博文中写得自己体会,修炼身心:在每天的不断重复学习中,耐住寂寞,练就真功,不畏艰 ...

  4. Node.js:fs文件模块的替代品fs-extra

    fs extra添加了本机fs模块中不包含的文件系统方法,并向fs方法添加了promise支持.它还使用优雅的fs来防止EMFILE错误.它应该是fs的替代品.(来自:百度翻译) 文档: npmjs: ...

  5. Node.js基础知识、fs、path、http三大模块、nodejs的模块化、npm与包管理

    文章目录 一.Node.js 简介 二.fs 文件系统模块 读取指定文件中的内容 向指定的文件中写入内容 案例-考试成绩整理 fs 模块 - 路径动态拼接的问题 三.path 路径模块 路径拼接 pa ...

  6. (12)Node.js核心模块fs—实现文件复制和压缩

    一.文件复制 将src目录下的style.css文件复制一份,到dist目录下. 二.文件压缩 文件压缩就是把我们书写的代码中的空格和注释进行删除,这样我们体积会变小,当我们上线到服务器时,给服务器造 ...

  7. (10)Node.js核心模块—fs文件系统之目录操作

    一.创建目录 // 引入fs模块 const fs = require('fs') //创建目录(文件夹) //语法:fs.mkdir('目录路径',回调函数) fs.mkdir('./d1', (e ...

  8. nodejs(五)node引入核心模块fs

    前面我们说ndoe引入自己的模块,相对路径要加 './',否则就会根据名字去引入核心模块,nodejs文件读写的核心模块是fs(file-system),引入方法: var fs = require( ...

  9. Node.js实战13:fs模块奥义!开发一个数据库。

    本文,将使用fs开发一种简单的文件型数据库. 数据库中,记录将采用JSON模式,内容型如: {"key":"a","value":" ...

  10. node基础学习——操作文件系统fs

    操作文件系统fs 1.在Node.js中,使用fs模块来实现所有有关文件及目录的创建.写入及删除.在fs模块中,所有对文件及目录的操作都可以使用同步与异步两种方法,具有Sync后缀的方法均为同步方法. ...

最新文章

  1. 基于Matlab的遗传算法优化BP神经网络在非线性函数拟合中的应用
  2. Openvswitch原理与代码分析(3): openvswitch内核模块的加载
  3. RabbitMQ 把一个queue从一个node转移到另外一个node.
  4. Google Map V3--geocode与fitBounds方法的同步操作
  5. Android 图形系统
  6. ubuntu11.10中配置OGRE1.8
  7. Codeforces | CF1029F 【Multicolored Markers】
  8. Flutter基础—绘画效果之装饰容器
  9. access ea 可以联网吗_EA自家Origin平台高级会员Origin Access Premier现已上线
  10. 基于python的学生信息管理系统文献综述_学生信息管理系统----文献综述
  11. FIT2CLOUD飞致云面试总结
  12. 百度ai—细粒度图像识别
  13. 如何在JMP中快速实现报表的个性化与可视化?
  14. 计算机怎么求标准偏差,如何计算Excel标准偏差?您必须知道这两个技巧
  15. 操作系统和指弹吉他的联系
  16. CubieBoard6(S500,armhf)安装ROS过程
  17. Python: 鲁卡斯队列
  18. 【机器学习】多分类学习的拆分策略
  19. Flutter系列之在 macOS 上安装和配置 Flutter 开发环境
  20. Python——连接数据库操作

热门文章

  1. 计算机毕业设计(59)php小程序毕设作品之点餐外卖小程序系统
  2. python中pandas处理csv_python – 处理pandas的问题读取csv
  3. html5 框架angularjs,5款最好用的AngularJS程序构建框架
  4. React Native集成极光消息推送
  5. dmp标签_今日头条新增DMP新标签,人群定向更简单!
  6. 龙腾15寸液晶屏M150GNN2 R1规格资料
  7. 2020安徽省程序设计大赛_收集圣物
  8. axios 拦截器分析
  9. 从《网安法》出发_给企业安全管理者的五条建议
  10. 我要自学网python教程推荐_我作文-这就是我作文、十年后的我作文大全