FED

©FrontEndDev.org
2015 - 2024
web@2.23.0 api@2.21.1

node 模块 fs-extra

fs-extra模块是系统fs模块的扩展,提供了更多便利的 API,并继承了fs模块的 API。

1、复制文件

copy(src, dest, [options], callback)

示例:

var fs = require('fs-extra');
 
fs.copy('/tmp/myfile', '/tmp/mynewfile', function(err) {
  if (err) return console.error(err)
  console.log("success!")
});
 
fs.copy('/tmp/mydir', '/tmp/mynewdir', function(err) {
  if (err) return console.error(err)
  console.log("success!")
});

2、创建文件、目录

ensureFile(file, callback)
createFile(file, callback)
createFileSync(file),
ensureFileSync(file)
ensureDir(dir, callback)
ensureDirSync(dir)

示例:

var fs = require('fs-extra');
 
var file = '/tmp/this/path/does/not/exist/file.txt'
fs.ensureFile(file, function(err) {
  console.log(err) // => null 
  //file has now been created, including the directory it is to be placed in 
});
 
var dir = '/tmp/this/path/does/not/exist'
fs.ensureDir(dir, function(err) {
  console.log(err) // => null 
  //dir has now been created, including the directory it is to be placed in 
});

3、移动文件、目录

move(src, dest, [options], callback)

示例:

var fs = require('fs-extra')
 
fs.move('/tmp/somefile', '/tmp/does/not/exist/yet/somefile', function(err) {
  if (err) return console.error(err)
  console.log("success!")
})

4、写入文件

outputFile(file, data, callback)

示例:

var fs = require('fs-extra')
var file = '/tmp/this/path/does/not/exist/file.txt'
 
fs.outputFile(file, 'hello!', function(err) {
  console.log(err) // => null 
 
  fs.readFile(file, 'utf8', function(err, data) {
    console.log(data) // => hello! 
  })
})

5、删除文件、目录

remove(dir, callback)

示例:

var fs = require('fs-extra')
 
fs.remove('/tmp/myfile', function(err) {
  if (err) return console.error(err)
  
  console.log("success!")
})
 
fs.removeSync('/home/jprichardson')