node 文件操作工具库 fs-extra

原文链接: node 文件操作工具库 fs-extra

上一篇: brotli js 压缩库

下一篇: nodejs 函数缓存库 memoizeOne 和 micro-memoize Memoizee

github

https://github.com/jprichardson/node-fs-extra

promise封装版, 比之前的回调函数更加顺手

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

支持 直接读写json, 更方便了

const fse = require('fs-extra')
const {
  copySync,
  emptyDirSync,
  ensureFileSync,
  ensureDirSync,
  ensureLinkSync,
  ensureSymlinkSync,
  mkdirpSync,
  mkdirsSync,
  moveSync,
  outputFileSync,
  outputJsonSync,
  pathExistsSync,
  readJsonSync,
  removeSync,
  writeJsonSync,
  readFileSync,
  writeFileSync
} = fse


// 目标文件夹不存在的话, 会自动创建, 方便!
copySync('./rxjs.js', 't/copy.js')

// 如果文件夹不存在, 会创建空文件夹
// 文件夹中含有其他文件或文件夹时会清空所有
// 创建时返回文件夹绝对路径
emptyDirSync('./empty2')

// 文件不存在则创建空文件, 存在时不做修改
// 永远返回undefined
ensureFileSync('./emp/t22.txt')

// 文件夹如果存在, 不做修改, 返回null
// 不存在时创建, 并返回文件夹绝对路径
ensureDirSync('./tmp2')

// 创建返回绝对路径
// 已经存在返回null
mkdirpSync('./ttt44/sas/aasd')

// 创建返回绝对路径
// 已经存在返回null
// 好像和上面一夜
mkdirsSync('./ttt55/sas/aasd2')

// 移动文件夹或文件, 源必须存在
// 无返回值
moveSync(
  './ttt',
  './tmp/may/already/existed/somedir',
  {overwrite: true}
)


// 读写
const file = './not/exist/file.txt'
// 无返回值
// 可设置编码, 文件路径不存在时会创建
// 两个方法效果一样
// outputFileSync(file, 'hello!','utf8')
writeFileSync(file, 'hello2!', 'utf8')

const data = readFileSync(file, 'utf8')
console.log(data) // => hello!

// output会创建不存在的文件夹
// outputJsonSync
let jsonPath = './t12.json'
// 可选设置项
// options <Object>
// spaces <Number|String> Number of spaces to indent; or a string to use for indentation (i.e. pass '\t' for tab indentation). See the docs for more info.
// EOL <String> Set EOL character. Default is \n.
// replacer JSON replacer
// Also accepts fs.writeFileSync options
// write 时文件路径必须存在.....,
// writeJsonSync(jsonPath,{name:"abc"})
outputJsonSync(jsonPath, {name: "abc"})
let obj = readJsonSync(jsonPath)
console.log(obj)

// 文件夹或文件路径是否存在
let e = pathExistsSync('./t')
console.log(e)

// 无返回值, 移除文件夹或文件, 递归式
removeSync('./t1.jpg')

Async

Sync

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值