一、writeFile函数的基本用法app
fs模块提供writeFile函数,能够异步的将数据写入一个文件, 若是文件已经存在则会被替换。
异步
var fs= require("fs"); //文件名, 内容, 回调函数 fs.writeFile('test.txt', 'Hello Node', function (err) { if (err) throw err; console.log('Saved successfully'); //文件被保存 });
数据参数能够是string或者是Buffer,编码格式参数可选,默认为"utf8",回调函数只有一个参数err。函数
二、appendFile函数的基本用法ui
writeFile函数虽然能够写入文件,可是若是文件已经存在,咱们只是想添加一部份内容,它就不能知足咱们的需求了,很幸运,fs模块中还有appendFile函数,它能够将新的内容追加到已有的文件中,若是文件不存在,则会建立一个新的文件编码
fs.appendFile('test.txt', 'data to append', function (err) { if (err) throw err; //数据被添加到文件的尾部 console.log('The "data to append" was appended to file!'); });
三、exists函数的基本用法spa
exists的回调函数只有一个参数,类型为布尔型,经过它来表示文件是否存在。code
fs.exists('test.txt', function (exists) { console.log(exists ? "存在" : "不存在!"); })
四、readFile函数的基本用法input
读取文件 回调函数里面的data,就是读取的文件内容。回调函数
fs.readFile('input.txt', function (err, data) { if (err) return console.error(err); console.log(data.toString()); });
五、unlink函数的基本用法string
文件删除函数
fs.unlink('test.txt', function (err) { if (err) throw err; console.log('successfully deleted'); });