fs-extra是更方便的fs包,用于处理各种文件,支持fs中的所有方法,项目中只用fs-extra就行了。当然如果你实在要用fs,两个一起用也没问题:
const fs = require('fs') const fse = require('fs-extra')
fs-extra中的方法,默认都是异步的,返回promise
- copy
- move
- remove
- emptyDir
- ensureFile,ensureDir
- ensureLink,ensureSymlink
- outputFile,outputJson
- pathExists
- readJson,writeJson
Copy
copy(src, dest, [options, callback]),如果src是目录,将拷贝目录下所有文件。如果src是文件,dest不能是目录。
options:
overwrite:bool,默认true
errorOnExist:bool,默认false,当为false且dest存在时抛出异常
dereference:bool,默认false
preserveTimestamps:bool,默认false
filter:function,过滤需要拷贝的文件,返回true为include,返回false为exclude
const path = require('path'); const fs = require('fs-extra'); const SRC = path.resolve(__dirname, '..'); const DEST = path.join(__dirname, '/tmp'); fs.copy(`${SRC}/chalk.js`, `${DEST}/chalk.js`, err => { // 拷贝文件(用 callback) if (err) return console.error(err); console.log('success!'); }); fs.copy(`${SRC}/inquirer`, `${DEST}/inquirer`, err => { // 拷贝文件夹 if (err) return console.error(err); console.log('success!'); }); fs.copy(`${SRC}/execa.js`, `${DEST}/execa.js`) // 拷贝文件(用 promise) .then(() => { console.log('success!'); }) .catch(err => { console.error(err); }); async function example () { // 拷贝文件(用 async/await) try { await fs.copy(`${SRC}/listr.js`, `${DEST}/listr.js`); console.log('success!'); } catch (err) { console.error(err); } } example(); const filterFunc = (src, dest) => { // 用过滤器 return /list/.test(src); // 为 true 才拷贝 }; fs.copy(`${SRC}/listr.js`, `${DEST}/listr.js`, { filter: filterFunc }, err => { if (err) return console.error(err); console.log('success!'); });
******** 后续方法都支持 callback promise async/await 这3种格式的写法。统一只展示 promise 的例子代码 ********
move
move(src, dest, [options, callback]),移动文件或文件夹。
const path = require('path'); const fs = require('fs-extra'); const srcpath = path.resolve(__dirname, 'dummy.js'); const dstpath = path.resolve(__dirname, 'tmp/this/path/does/not/exist/dummy.js'); fs.move(srcpath, dstpath) .then(() => { console.log('success!'); }) .catch(err => { console.error(err); }); fs.move(srcpath, dstpath, { overwrite: true }, err => { // 也可以带着 option if (err) return console.error(err); console.log('success!'); });
remove
remove(path, [callback]),删除文件或文件夹,类似rm -rf
const path = require('path'); const fs = require('fs-extra'); const file = path.join(__dirname, 'tmp/chalk.js'); fs.remove(file) .then(() => { console.log('success!'); }) .catch(err => { console.error(err); });
emptyDir
emptyDir(dir, [callback]),清空目录中的文件。如果目录不存在,就创建一个空目录。
const path = require('path'); const fs = require('fs-extra'); const SRC = path.resolve(__dirname, 'tmp'); fs.emptyDir(SRC) .then(() => { console.log('success!'); }) .catch(err => { console.error(err); });
ensureFile & ensureDir
ensureFile(file, [callback]),确保文件存在。如果文件不存在,就创建这些目录,并创建空文件。如果文件已经存在,不修改它。
ensureDir(dir[,options][,callback]),确保文件夹存在。如果文件夹不存在,就创建,等价于:mkdir -p。
const path = require('path'); const fs = require('fs-extra'); const SRC = path.resolve(__dirname, 'tmp'); const file = `${SRC}/this/path/does/not/exist/file.txt`; const dir = `${SRC}/this/path/does/not/exist`; const desiredMode = 0o2775; const options = { mode: 0o2775 }; fs.ensureFile(file) .then(() => { console.log('success!'); }) .catch(err => { console.error(err); }); 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 }); async function exampleMode (directory) { try { await fs.ensureDir(directory, options); console.log('success!'); } catch (err) { console.error(err); } } exampleMode(dir);
ensureLink & ensureSymlink
ensureLink(srcpath, dstpath, [callback]),确保link存在。如果文件夹不存在,就创建。
ensureSymlink(srcpath, dstpath, [type, callback]),确保symlink存在。如果文件夹不存在,就创建。
const path = require('path'); const fs = require('fs-extra'); const srcpath = path.resolve(__dirname, 'copy.js'); const dstpath = path.resolve(__dirname, 'tmp/this/path/does/not/exist/copy.js'); fs.ensureLink(srcpath, dstpath) .then(() => { console.log('success!'); }) .catch(err => { console.error(err); }); fs.ensureSymlink(srcpath, dstpath) .then(() => { console.log('success!'); }) .catch(err => { console.error(err); });
outputFile & outputJson
outputFile(file, data, [options, callback]),类似fs.writeFile(),写文件,会直接覆盖文件。如果文件不存在会创建。
outputJson(file, object, [options, callback]),类似fs.writeJson(),写文件,会直接覆盖文件。如果文件不存在会创建。
const path = require('path'); const fs = require('fs-extra'); const file = path.join(__dirname, 'tmp/file.txt'); const jsonFile = path.join(__dirname, 'tmp/file.json'); fs.outputFile(file, 'hello2!') .then(() => fs.readFile(file, 'utf8')) .then(data => { console.log(data); // => hello2! }) .catch(err => { console.error(err); }); fs.outputJson(jsonFile, {name: 'JP'}) .then(() => fs.readJson(jsonFile)) .then(data => { console.log(data.name); // => JP }) .catch(err => { console.error(err); });
pathExists
pathExists(file[, callback]),判断路径是否存在,类似fs.exists。
const path = require('path'); const fs = require('fs-extra'); const file = path.join(__dirname, 'tmp/asdfghjk.txt'); fs.pathExists(file) .then(exists => console.log(exists)); // => false
readJson & writeJson
readJson(file, [options, callback]),读取Json文件,并转成object。
writeJson(file, object, [options, callback]),将object写入Json文件。
const path = require('path'); const fs = require('fs-extra'); const file = path.resolve(__dirname, '../../package.json'); fs.readJson(file) .then(packageObj => { console.log(packageObj.version); // => 1.0.0 }) .catch(err => { console.error(err); }); // 可以携带一个 { throws: false } 的option,即使Json不合法也不会抛异常 const file2 = path.join(__dirname, 'tmp/some-invalid.json'); const data = '{not valid JSON'; fs.writeFileSync(file2, data); fs.readJson(file2, { throws: false }) .then(obj => { console.log(obj); // => null }) .catch(err => { console.error(err); // Not called }); // writeJson const file3 = path.resolve(__dirname, 'tmp/package.json'); fs.writeJson(file, {name: 'fs-extra'}) .then(() => { console.log('success!'); }) .catch(err => { console.error(err); });