const fs = require("fs");
const fsExtra = require("fs-extra");
const path = require("path");
const writeFile = (filepath, content) => {
fs.writeFile(filepath, content, (err) => {
if (err) {
console.error(err);
return;
}
});
};
writeFile("../assets/test.txt", "node.js写入文件数据1\n");
const appFile = (filepath, content) => {
fs.appendFile(filepath, content, (err) => {
if (err) {
return console.error(err);
}
});
};
appFile("../assets/test.txt", "node.js追加文件数据1\n");
appFile("../assets/test.txt", "node.js追加文件数据2\n");
const readFile = async (filepath) => {
const content = await fs.promises
.readFile(filepath, "utf8")
.catch((err) => console.error("failed to read file", err));
return content;
};
readFile("../assets/test.txt").then((content) => {
console.log("content=>", content);
});
const getFileInfo = async (filepath) => {
const stat = await fs.promises.stat(filepath).catch((err) => {
console.log("failed to read file", err);
});
return stat;
};
getFileInfo("../assets/test.txt").then((stat) => {
console.log("file size =" + stat.size);
console.log("Is a file", stat.isFile());
});
const listFiles = async (folderpath) => {
const fileList = await fs.promises.readdir(folderpath).catch((err) => {
console.error("failed to read dir", err);
});
return fileList;
};
listFiles("../assets").then((fileList) => {
console.log(JSON.stringify(fileList, null, " "));
});
const copyFolder = async (folderpathSrc, folderpathDest) => {
await fsExtra.copy(folderpathSrc, folderpathDest).catch((err) => {
console.error("failed to copy dir", err);
});
};
copyFolder("../assets", "../assets-bak");
const removeFolder = async (folderpath) => {
await fsExtra.remove(folderpath).catch((err) => {
console.log("failed to remove dir", err);
});
};
removeFolder("../assets-bak");
const parsePath = (filepath) => {
return {
dirname: path.dirname(filepath),
basename: path.basename(filepath),
extname: path.extname(filepath),
};
};
const pathObj = parsePath("/user/larry/test.txt");
console.log(JSON.stringify(pathObj, null, " "));