Node 之 使用文件模块操作
安装
shell
pnpm add fs-extra -S
pnpm add @types/fs-extra -D用法
应该是
应该总是fs-extra代替fs使用,所有fs方法都附在fs-extra,fs如果未传递回调,则所有方法都将返回promise。
ts
import * as fs from "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
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 (别名:emptydirSync)
- ensureFileSync
- ensureDirSync (别名:mkdirpSync、mkdirsSync)
- ensureLinkSync
- ensureSymlinkSync
- mkdirpSync
- mkdirsSync
- moveSync
- outputFileSync
- outputJsonSync (别名:outputJSONSync)
- pathExistsSync
- readJsonSync (别名:readJSONSync)
- removeSync
- writeJsonSync (别名:writeJSONSync)
API 详解
copy
复制文件或目录,目录可以包含内容,类似 cp -r
bash
copy(src: string, dest: string, options: object, callback: func)src 请注意,如果src是目录,它将复制此目录内的所有内容,而不是整个目录本身
dest 请注意,如果src是文件,dest则不能是目录
options
- filter: 过滤复制文件的功能。返回true包含,false排除。也可以返回Promise解析为true或false(或传入async函数)
- overwrite: boolean 覆盖现有文件或目录,默认为true。请注意,如果将此设置为false并且目标存在,则复制操作将无提示失败。使用该errorOnExist选项可更改此行为。
- errorOnExist: boolean 当overwrite为false和目标存在时,抛出错误。默认是false。
- dereference: boolean dereference symlinks,默认是false。
- preserveTimestamps: boolean 如果为true,将设置对原始源文件的最后修改和访问时间。如果为false,则时间戳行为取决于操作系统。默认是false。
- recursive: boolean
- process: function (src: string, dest: string) => void
callback 回调函数
代码
ts
import * as fs from "fs-extra";
// 异步方法返回一个promise
async function copyFile(oldurl: string, newurl: string) {
const result = await fs.copy(oldurl, newurl, {
overwrite: true,
errorOnExist: false,
filter: filterFunc,
});
console.log("success");
}
// 过滤函数 过滤掉里面含
const filterFunc = (srcPath: string, destPath: string): boolean => {
// 获取文件名(包含扩展名)
const fileName = srcPath.split("/").pop() || srcPath.split("\\").pop();
// 如果文件名包含 "text",则返回 false(不复制)
if (fileName && fileName.includes("test")) {
console.log(`跳过文件: ${srcPath}`);
return false;
}
return true;
};
copyFile("./src", "./copy");emptyDir
确保目录为空。如果目录不为空,则删除目录内容。如果该目录不存在,则创建该目录。目录本身不会被删除。
ts
emptyDir(path: string, callback: func)- path
- callback
ts
import * as fs from "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();ensureFile
确保文件存在。如果文件不存在,则创建文件。如果文件存在,则不执行任何操作。
ts
ensureFile(file: string, callback: func)- file
- callback
ts
import * as fs from "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);ensureDir
确保目录存在。如果目录不存在,则创建目录。如果目录存在,则不执行任何操作。
ts
ensureDir(path: string, callback: func)- path
- callback
ts
import * as fs from "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);ensureLink
确保符号链接存在。如果符号链接不存在,则创建符号链接。如果符号链接存在,则不执行任何操作。
ts
ensureLink(src: string, dest: string, callback: func)- src 源路径
- dest 目标路径
- callback 回调函数
ts
import * as fs from "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);ensureSymlink
确保符号链接存在。如果符号链接不存在,则创建符号链接。如果符号链接存在,则不执行任何操作。
ts
ensureSymlink(src: string, dest: string, callback: func)- src 源路径
- dest 目标路径
- callback 回调函数
ts
import * as fs from "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);move
移动文件或目录,甚至跨设备。 类似 mv
ts
move(src: string, dest: string, options:object,callback: func)- src 源路径
- dest 目标路径
- options
- overwrite : 覆盖现有文件或目录,默认为false。
- callback 回调函数
ts
import * as fs from "fs-extra";
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);outputFile
几乎与writeFile(即它覆盖)相同,除了如果父目录不存在,则创建它。file必须是文件路径(不允许使用缓冲区或文件描述符)。
ts
outputJson(file: string, object:object, options:object, callback: func)- file 写入文件路径
- data 写入文件的数据
- options
- encoding | 默认为 'utf8'
- mode 默认为 0o666
- flag 详见支持的文件系统flag, 默认为 'w'
- callback 回调方法
ts
import * as fs from "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);outputJson
几乎与writeJson相同,除了如果父目录不存在,则创建它。
- file 写入文件路径
- data 写入文件的数据
- options
- encoding | 默认为 'utf8'
- mode 默认为 0o666
- flag 详见支持的文件系统flag, 默认为 'w'
- spaces <number|string> 缩进的空格数; 或者用于缩进的字符串(即传递'\t'标签缩进)
- EOL 设置EOL字符。默认是\n。
- replacer JSON replacer
- callback 回调方法
ts
import * as fs from "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);pathExists
通过检查文件系统来测试给定路径是否存在。类似fs.exists
ts
pathExists(file: string [, callback: func])- file 文件路径
- callback 回调函数
ts
import * as fs from "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);readJson
读取JSON文件,然后将其解析为对象
file JSON路径
options
- throws 如果为false 并且JSON无效, 它将不会抛出err,默认为true
callback 回调函数
ts
import * as fs from "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();remove
删除文件或目录。如果目录存在,则递归删除目录和文件。
path 目标路径
callback 回调函数
ts
import * as fs from "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();writeJson
将对象写入JSON文件, 几乎与outputJson相同,除了必须保证目录存在外。
- file 写入文件路径
- object 写入文件的JSON对象
- options
- encoding | 默认为 'utf8'
- mode 默认为 0o666
- flag 详见支持的文件系统flag, 默认为 'w'
- spaces <number|string> 缩进的空格数; 或者用于缩进的字符串(即传递'\t'标签缩进)
- EOL 设置EOL字符。默认是\n。
- replacer JSON replacer
callback 回调方法
ts
import * as fs from "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();