当前位置: 首页 > 工具软件 > node-fs > 使用案例 >

Node-fs模块

齐甫
2023-12-01

1.操作文件夹

1.1创建文件夹 增(非promise)

  • 返回值:成功:undefined;失败:错误对象

1.1.1异步

  • fs.mkdir('创建的文件夹(路径+名称)',(err)=>{})
let fs = require('fs');
fs.mkdir('../logs', (err) => {//优先错误打印
  if (err) {
    throw err;
  } else {
    console.log('文件夹创建成功');
  }
});
console.log('正常执行');//优先打印 正常执行

1.1.2同步

  • let res=fs.mkdirSync('创建的文件夹(路径+名称)',{recursive: false,mode: 0o777})
let fs = require('fs');
let res=fs.mkdirSync('../logs',{
  recursive: false,
  mode: 0o777,
})
console.log(res);//顺序打印 正常就是undefined 报错就是打印错误对象
console.log('正常执行');//顺序打印

1.1.3封装

let fs = require('fs');
function mkdir(UrlName, bool = false, params = { recursive: false, mode: 0o777 }) {//默认异步创建文件夹
  if (bool) {//同步创建文件夹
    return fs.mkdirSync(UrlName, params);
  } else {
    return new Promise((resolve, reject) => {
      fs.mkdir(UrlName, (err) => {//优先错误打印
        if (err) {
          reject(err)
        } else {
          resolve('文件夹创建成功')
        }
      });
    })
  }
}
//调用方法一:调用异步
mkdir('../logs').then((res) => {
  console.log(res);
}).catch(err => {
  console.log(err);
});
//调用方法二:调用同步
let res=mkdir('../logs',true);
console.log(res);

1.2创建文件夹 增(promise)

1.2.1基本使用

let fsPromises = require('fs').promises;
let res = fspPromises.mkdir('../logs', {
  recursive: false,
  mode: 0o777
});//返回的是一个promise对象

res.then(res => {
  console.log(res);
}).catch(err => {
  console.log(err);
});

1.2.2async/await方法

let fsPromises = require('fs').promises;
async function fn(url) {
  let res = await fspPromises.mkdir(url,{
  	recursive: false,
  	mode: 0o777
  });
  console.log(res);
};
fn('../logs');

1.3删除文件夹 删(非promise)

  • 返回值:成功:undefined;失败:错误对象

1.3.1异步

  • fs.rmdir('删除的文件夹(路径+名称)',err=>{})
let fs = require('fs');
fs.rmdir('../logs', (err) => {//优先错误打印
  if (err) {
    throw err;
  } else {
    console.log('文件删除成功');
  }
})
console.log('正常打印');//优先打印

1.3.2同步

  • fs.rmdirSync('删除的文件夹(路径+名称)',{maxRetries: 0,recursive: false,retryDelay: 100})
let fs = require('fs');
let res = fs.rmdirSync('../logs', {
  maxRetries: 0,
  recursive: false,
  retryDelay: 100
})
console.log(res);//顺序打印 正常就是undefined 报错就是打印错误对象
console.log('正常执行');//顺序打印

1.3.3封装

let fs = require('fs');
function rmdir(UrlName, bool = false, params = {
  maxRetries: 0,
  recursive: false,
  retryDelay: 100
}) {//默认异步
  if (bool) {//同步
    return fs.rmdirSync(UrlName, params)
  } else {
    return new Promise((resolve, reject) => {
      fs.rmdir(UrlName, (err) => {
        if (err) {
          reject(err)
        } else {
          resolve('文件删除成功');
        }
      })
    })
  }
};
//调用方法一:调用异步
rmdir('../logs').then((res) => {
  console.log(res);
}).catch(err => {
  console.log(err);
});
//调用方法二:调用同步
let res=rmdir('../logs',true);
console.log(res);

1.4删除文件夹 删(promise)

1.4.1基本使用

let fsPromises = require('fs').promises;
let res = fsPromises.rmdir('../logs', {
  maxRetries: 0,
  recursive: false,
  retryDelay: 100
});
res.then(res => {
  console.log(res);
}).catch(err => {
  console.log(err);
});

1.4.2async/await方法

let fsPromises = require('fs').promises;
async function fn(url) {
  let res = await fsPromises.rmdir(url, {
    maxRetries: 0,
    recursive: false,
    retryDelay: 100
  });
  console.log(res);
};
fn('../logs');

1.5重命名文件夹 改(非promise)

  • 返回值:成功:undefined;失败:错误对象

1.5.1异步

  • fs.rename('需要重命名的文件夹(路径+名称)','新的的文件夹(路径+名称)',(err)=>{})
let fs = require('fs');
fs.rename('../logs', '../log', (err) => {//优先错误打印
  if (err) {
    throw err;
  }else{
    console.log('文件重命名成功');
  }
})
console.log('顺序执行');//优先打印

1.5.2同步

  • let res=fs.renameSync('需要重命名的文件夹(路径+名称)','新的的文件夹(路径+名称)')
let fs = require('fs');
let res = fs.renameSync('../logs', '../log');
console.log(res);
console.log('顺序执行');//顺序执行

1.5.3封装

function rename(UrlName, newUrlName,bool = false, ) {//默认异步
  if (bool) {//同步
    return fs.renameSync(UrlName, newUrlName)
  } else {
    return new Promise((resolve, reject) => {
      fs.rename(UrlName, newUrlName, (err) => {
        if (err) {
          reject(err)
        } else {
          resolve('文件重命名成功');
        }
      })
    })
  }
};
//调用方法一:调用异步
rename('../logs', '../log').then((res) => {
  console.log(res);
}).catch(err => {
  console.log(err);
});
//调用方法一:调用同步
let res = rename('../logs', '../log',true);
console.log(res);

1.6重命名文件夹 改(promise)

1.6.1基本使用

let fsPromises = require('fs').promises;
let res = fsPromises.rename('../logs', '../log');
res.then(res => {
  console.log(res);
}).catch(err => {
  console.log(err);
})

1.6.2async/await方法

let fsPromises = require('fs').promises;
async function fn(url, newUrl) {
  let res = await fsPromises.rename(url, newUrl);
  console.log(res);
};
fn('../log', '../logs')

1.7读取文件夹内容 查(非promise)

  • 返回值:成功由该文件夹下所有组件组成的数组;失败:错误对象

1.7.1异步

  • fs.readdir('读取的文件夹(路径+名称)',(err,res)=>{})
let fs = require('fs');
fs.readdir('../data', (err, res) => {//优先错误打印
  if (err) {
    throw err;
  }else{
    console.log(res);//['url.json']
  }
});
console.log('顺序执行');//优先执行

1.7.2同步

  • let res=fs.readdirSync('读取的文件夹(路径+名称)',{encoding: 'utf8',withFileTypes: false})
let fs = require('fs');
let res = fs.readdirSync('../data', {
  encoding: 'utf8',
  withFileTypes: false
});
console.log(res);//['url.json']
console.log('顺序执行');//顺序执行

1.7.3封装

let fs = require('fs');
function readdir(UrlName, bool = false, params = {
  encoding: 'utf8',
  withFileTypes: false
}) {//默认异步
  if (bool) {//同步
    return fs.readdirSync(UrlName, params)
  } else {
    return new Promise((resolve, reject) => {
      fs.readdir(UrlName, (err, res) => {//优先错误打印
        if (err) {
          reject(err)
        } else {
          resolve(res);
        }
      })
    })
  }
}
readdir('../data').then((res) => {
  console.log(res);//['url.json']
}).catch(err => {
  console.log(err);
});

let res = readdir('../data', true);
console.log(res);//['url.json']

1.8读取文件夹内容 查(promise)

1.8.1基本使用

let fsPromises = require('fs').promises;
let res = fsPromises.readdir('../logs', {
  encoding: 'utf8',
  withFileTypes: false
});
res.then(res => {
  console.log(res);//[ 'dd.html' ]
}).catch(err => {
  console.log(err);
})

1.8.2async/await方法

let fsPromises = require('fs').promises;
async function fn(url) {
  let res = await fsPromises.readdir(url, {
    encoding: 'utf8',
    withFileTypes: false
  });
  console.log(res);//[ 'dd.html' ]
};
fn('../logs');

1.9综合实例

//使用同步方式创建
mkdir('../logs', true);//创建文件夹
let res = readdir('../logs', true);//读取文件夹内容
console.log(res);//[]
rename('../logs', '../log', true);//重命名文件夹
rmdir('../log', true);//删除文件夹

//使用异步方式创建
mkdir('../logs').then(res => {
  console.log(res);//文件夹创建成功
  return readdir('../logs');
}).then(res => {
  console.log(res);//[]
  return rename('../logs','../log');
}).then(res=>{
  console.log(res);//文件重命名成功
  return rmdir('../log')
}).then(res=>{
  console.log(res);//文件删除成功
}).catch(err => {
  console.log(err);
})

//使用async/await方式创建
async function fn() {
  let res1 = await mkdir('../logs');
  let res2 = await readdir('../logs');
  let res3 = await rename('../logs', '../log');
  let res4 = await rmdir('../log');
  console.log(res1, res2, res3, res4);//文件夹创建成功 [] 文件重命名成功 文件删除成功
}
fn();

2.操作文件

2.1创建文件 增(非promise)

2.1.1异步

let fs = require('fs');
fs.writeFile('../logs/log1.log', 'hello\nworld!', {
  encoding: 'utf8',
  mode: 0o666,
  flag: 'w'
}, (err) => {
  if (err) {
    console.log('写入文件失败');
  } else {
    console.log('写入文件成功');
  }
})

2.1.2同步

let res = fs.writeFileSync('../logs/log1.log', 'hello\nworld2', {
  encoding: 'utf8',
  mode: 0o666,
  flag: 'w'
});
console.log(res);

2.1.3封装

function writeFile(url, data, bool = false, params = {
  encoding: 'utf8',
  mode: 0o666,
  flag: 'w'
}) {
  if (bool) {
    return fs.writeFileSync(url, data, params)
  } else {
    return new Promise((resolve, reject) => {
      fs.writeFile(url, data, params, err => {
        if (err) {
          reject(err)
        } else {
          resolve('写入文件成功')
        }
      })
    })
  }
};
//调用方法一
writeFile('../logs/log2.log', '996').then(res => {
  console.log(res);
}).catch(err => {
  console.log(err);
});
//调用方法二
let res = writeFile('../logs/log2.log', '886', true);
console.log(res);

2.2创建文件 增(promise)

2.2.1基本使用

let fsPromises = require('fs').promises;
let res = fsPromises.writeFile('../logs/log3.log', '123', {
  encoding: 'utf8',
  mode: 0o666,
  flag: 'w'
});
res.then(res => {
  console.log(res);
}).catch(err => {
  console.log(err);
});

2.2.2async/await方法

let fsPromises = require('fs').promises;
async function fn(url, data) {
  let res = await fsPromises.writeFile(url, data, {
    encoding: 'utf8',
    mode: 0o666,
    flag: 'w'
  });
  console.log(res);
};
fn('../logs/log4.log', '123');

2.3追加文件 增(非promise)

2.3.1异步

let fs = require('fs');
fs.appendFile('../logs/log5.log', '456', {
  encoding: 'utf8',
  mode: 0o666,
  flag: 'a'
}, err => {
  if (err) {
    throw err;
  } else {
    console.log('追加文件失败');
  }
});

2.3.2同步

let res = fs.appendFileSync('../logs/log5.log', '789', {
  encoding: 'utf8',
  mode: 0o666,
  flag: 'a'
});
console.log(res);

2.3.3封装

function appendFile(url, data, bool = false, params = {
  encoding: 'utf8',
  mode: 0o666,
  flag: 'a'
}) {
  if (bool) {
    return fs.appendFileSync(url, data, params);
  } else {
    return new Promise((resolve, reject) => {
      fs.appendFile(url, data, params, err => {
        if (err) {
          reject(err)
        } else {
          resolve('追加文件成功')
        }
      })
    })
  }
};
//调用方法一
appendFile('../logs/log6.log', '996663').then(res => {
  console.log(res);
}).catch(err => {
  console.log(err);
});
//调用方法二
let res = appendFile('../logs/log61.log', '99666336', true);
console.log(res);

2.4追加文件 增(promise)

2.4.1基本使用

let fsPromises = require('fs').promises;
let res = fsPromises.writeFile('../logs/log10.log', '963', {
  encoding: 'utf8',
  mode: 0o666,
  flag: 'a'
});
res.then(res => {
  console.log(res);
}).catch(err => {
  console.log(err);
})

2.4.2async/await方法

let fsPromises = require('fs').promises;
async function fn(url, data) {
  let res = await fsPromises.writeFile(url, data, {
    encoding: 'utf8',
    mode: 0o666,
    flag: 'a'
  });
  console.log(res);
}
fn('../logs/log101.log', '963');

2.5删除文件 删(非promise)

2.5.1异步

let fs = require('fs');
fs.unlink('../logs/log10.log', err => {
  if (err) {
    throw err;
  } else {
    console.log('删除文件成功');
  }
});

5.2.2同步

let fs = require('fs');
let res = fs.unlinkSync('../logs/log6.log');
console.log(res);

5.2.3封装

let fs = require('fs');
function unlink(url, bool = false) {
  if (bool) {
    return fs.unlinkSync(url)
  } else {
    return new Promise((resolve, reject) => {
      fs.unlink(url, err => {
        if (err) {
          reject(err)
        } else {
          resolve('删除文件成功')
        }
      })
    })
  }
};
//调用方法一
unlink('../logs/log101.log').then(res => {
  console.log(res);
}).catch(err => {
  console.log(err);
});
//调用方法二
let res = unlink('../logs/log4.log', true);
console.log(res);

2.6删除文件 删(promise)

2.6.1基本使用

let fsPromises = require('fs').promises;
let res = fsPromises.unlink('../logs/log61.log');
res.then(res => {
  console.log(res);
}).catch(err => {
  console.log(err);
});

2.6.2async/await方法

let fsPromises = require('fs').promises;
async function fn(url) {
  let res = await fsPromises.unlink(url);
  console.log(res);
}
fn('../logs/log1.log')

2.7读取文件 读(非promise)

异步

let fs = require('fs');
fs.readFile('../logs/log2.log', {
  encoding: null,
  flag: 'r'
}, (err, data) => {
  if (err) {
    throw err;
  } else {
    console.log(data.toString());
  }
})

同步

let res = fs.readFileSync('../logs/log2.log', {
  encoding: null,
  flag: 'r'
});
console.log(res.toString());

封装

function readFile(url, bool = false, params = {
  encoding: null,
  flag: 'r'
}) {
  if (bool) {
    return fs.readFileSync(url, params);
  } else {
    return new Promise((resolve, reject) => {
      fs.readFile(url, params, (err, data) => {
        if (err) {
          reject(err)
        } else {
          resolve(data)
        }
      })
    })
  }
};
//调用方法一
let res = readFile('../logs/log2.log');
res.then(res => {
  console.log(res.toString());
}).catch(err => {
  console.log(err);
})
//调用方法二
let res = readFile('../logs/log2.log', true);
console.log(res.toString());

读取文件 读(promise)

基本使用

let fsPromises = require('fs').promises;
let res = fsPromises.readFile('../logs/log2.log', {
  encoding: null,
  flag: 'r'
});
res.then(res => {
  console.log(res.toString());
}).catch(err => {
  console.log(err);
});

async/await方法

let fsPromises = require('fs').promises;
async function fn(url) {
  let res = await fsPromises.readFile(url, {
    encoding: null,
    flag: 'r'
  });
  console.log(res.toString());
}
fn('../logs/log2.log');

删除文件夹(无论它存不存在内容)

function deepRmdir(url) {
  if (fs.existsSync(url)) {//判断路径是否存在
    let delArr = fs.readdirSync(url);
    delArr.forEach(item => {
      if (fs.statSync(`${url}/${item}`).isDirectory()) {
        deepRmdir(`${url}/${item}`);
      } else {
        fs.unlinkSync(`${url}/${item}`)
      }
    });
    fs.rmdirSync(url);
  } else {
    console.log('路径不存在');
  }
};

读取文件夹下的内容

function deepReadDir(url) {
  if (fs.existsSync(url)) {//判断路径是否存在
    let fileArr = fs.readdirSync(url);
    fileArr.forEach(item => {
      if (fs.statSync(`${url}/${item}`).isDirectory()) {
        deepReadDir(`${url}/${item}`)
      } else {
        let res = fs.readFileSync(`${url}/${item}`);
        console.log(res.toString());
      }
    })
  } else {
    console.log('路径不存在');
  }
};
 类似资料: