内置模块fs
- mkdir:创建文件夹
- rmdir:删除文件夹
- rename:重命名文件夹或文件
- readir:读取文件夹下的内容
- writeFile:写文件
- appendFile:在文件中追加内容
- unlink:删除文件
- readFile:异步读取文件
- readFileSync:同步读取文件
- watch:监听目录或文件变化 文档
const fs = require('fs');
// import { readFile } from 'fs/promises';
//创建文件夹
// fs.mkdir('logs', err => {
// if (err) throw err;
// console.log('文件夹创建成功');
// });
//删除文件夹
// fs.rmdir('logs', () => {
// console.log('文件夹删除成功');
// });
//重命名文件夹或文件
// fs.rename('./logs', './log', () => {
// console.log('文件夹重命名成功');
// });
//读取文件夹下的内容
// fs.readdir(__dirname + '/log', (err, result) => {
// console.log(result);
// });
// 写文件
// fs.writeFile('./log/log1.log', 'hello\nworld', err => {
// console.log('done');
// });
//在文件中追加内容
// fs.appendFile('./log/log1.log', '!!!', err => {
// console.log('追加内容成功');
// });
//删除文件
// fs.unlink('./log/log1.log', err => {
// console.log('文件删除成功');
// });
//异步读取文件1
// fs.readFile('./log/log1.log', 'utf-8', (err, content) => {
// console.log(content);
// })
//异步读取文件2
// fs.readFile('./log/log1.log', (err, content) => {
// console.log(content.toString());
// });;
//同步读取文件
// const content = fs.readFileSync('./log/log1.log');
// console.log(content.toString());
// console.log('continue...');
//返回promise
// (async () => {
// const content = await readFile('./log/log1.log');
// console.log(content.toString());
// })();
// for (let i = 0; i < 10; i++){
// fs.writeFile(`./log/log${i}.log`, 'hello world!', err => {
// console.log('done');
// });
// }
//监听目录或文件变化
fs.watch(__dirname + '/log/log1.log', (err, content) => {
console.log('file has changed');
});