1. renameSync
01. 重命名
02. 移动文件夹,相当于剪切作用
var fs = require('fs');
// 01 文件重命名
var renameFile = (oldFile,newFile) =>{
let result = fs.renameSync(oldFile,newFile);
if(!result){
console.log(`${oldFile}文件名成功修改为${newFile}`);
}
}
renameFile('./js/01 test.js','./js/01 tested.js'); //02 文件夹移动 将js文件夹移动到public目录下
function rename(oldPath,newPath){
var result = fs.renameSync(oldPath,newPath);
if(!result){
console.log(`${oldPath}已经移入新文件夹`);
}
}
rename('./public/js','./js');
2. watch
//03 watch 文件 文件夹监听
/* 监听文件夹
>01.fs.watch(dirname,listener)
>02.dirname:文件夹路径/文件路径
>03.listener(event,filename)
>04.event:'rename/change'
>05.filename:改变的文件名
*/
function listener(event, filename) { console.log('event', event)
console.log('filename', filename)
} function watch(dirname) {
fs.watch(dirname, listener);
console.log(`监听目录${dirname}`);
}
watch('./js');
3. watchFile
//04 watchFile
/*监听文件
>01.fs.watchFile(filename,listener)
>02.filename:文件路径
>03.listener(curr,prev)
>04.curr:当前文件
>05.prev:之前文件
>06.fs.unwatchFile(filename,listener)
*/
var listener2 = (current,prev)=>{
console.log('event',current);
console.log('filename',prev)
}
var watchFile = (dirname)=>{
fs.watchFile(dirname,listener2);
console.log(`开始监听文件${dirname}`)
}
watchFile('./js/01 tested.js');
4. unwatchFile
配合watchFile使用
//04 watchFile
/*监听文件
>01.fs.watchFile(filename,listener)
>02.filename:文件路径
>03.listener(curr,prev)
>04.curr:当前文件
>05.prev:之前文件
>06.fs.unwatchFile(filename,listener)
*/
var listener2 = (current,prev)=>{
console.log('event',current);
console.log('filename',prev)
}
var watchFile = (filename)=>{
fs.watchFile(filename,listener2);
console.log(`开始监听文件${filename}`)
}
watchFile('./js/01 tested.js'); //05 unwatchFile文件监听解除
var unwatchFile =(filename,listener)=>{
fs.unwatchFile(filename,listener);
} setTimeout(()=>{
unwatchFile('./js/01 tested.js',listener2);
console.log('停止监听')
},20000)