node学习笔记3,文件系统

140 阅读1分钟

首先需要引入fs模块
var fs = require("fs");

fs.open(文件的路径,文件打开的方式读/写[, mode设置文件模式(权限)], callback回调函数)打开文件
fs.open("./03file/1.txt","r",function (err,fd) {
if (err ==true){
console.log("文件打开失败");
}else {
console.log("文件打开成功");
console.log(err);
 console.log(fd);
 }
});多次打开返回的fd是不同的

打开后读取文件内容用fs.read(fd, buffer, offset, length, position, callback)



fs.write(fd, buffer, offset, length[, position], callback)
将缓冲区内容写入到通过文件描述符指定的文件




fs.appendFile(filename,"__我是追加的内容!",function () { });在原有文件的基础上追加内容。


删除文件  fs.unlink(filename,function (err) {
console.log(err);//不报错就是null
  if (err ==null){
console.log("shanchuan chenggong !");
 }else {
console.log("shibai"); }
});


var filename ="./03file/1.txt";//先声明一个文件名及路径
fs.writeFileSync(filename,"123",function () { });先创建一个文件,里面写入123
fs.renameSync(filename,"./03file/2.txt",function () {   //再修改文件名为同目录下2.txt
console.log("rename success!"); });


fs.stat("./03file/2.txt",function () {
console.log(arguments);
});//返回文件的状态信息


fs.mkdir("./03file/1",function () {
 console.log(arguments);
});   创建一个文件夹
fs.rmdir("./03file/1",function () {
    console.log(arguments);
});  删除一个文件夹,只能删除空文件夹


fs.readdir("./03file",function (err,list) {
console.log(err);
    console.log(list);
});读取目录下都有什么文件