fs模块封装了对文件操作的各种方法,比如同步和异步读写、批量操作、流、监听。
我们还是通常例程学习,
获取目录下的文件清单:
var fs =require("fs"); fs.readdir("./",function(err,files){ console.log(files); })
输出如下:
再来一例:
向文件同步写入内容,再同步读出:
var fs = require("fs"); var assert = require("assert"); //同步写入 var fd = fs.openSync("./test.txt","w+"); var write_buf = new Buffer("something to write"); fs.writeSync(fd,write_buf,0,write_buf.length,0); //同步读取 var read_buf = new Buffer(write_buf.length); fs.readSync(fd,read_buf,0,write_buf.length,0); console.log(read_buf.toString()); //用断言asset比较写入和读取的内容是否一至 assert.equal(write_buf.toString(),read_buf.toString()); fs.closeSync(fd);
假如断言这句改为:
则会输出错误信息: