node.js和其他语言一样,也有文件操作。先不说node.js中的文件操作,其他语言的文件操作一般也都是有打开、关闭、读、写、文件信息、新建删除目录、删除文件、检测文件路径等。在node.js中也是一样,也都是这些功能,可能就是api与其他语言不太一样。
一、同步、异步打开关闭
/** * created by administrator on 2016/3/21. */var fs=require(fs);//同步读 fs.opensync = function(path, flags, mode)//模块fs.js文件中如上面定义的opensync 函数3个参数//.1.path 文件路径//2.flags 打开文件的模式//3.model 设置文件访问模式//fd文件描述var fd=fs.opensync(data/openclose.txt,'w');//fs.closesync = function(fd)fs.closesync(fd);//异步读写//fs.open = function(path, flags, mode, callback_)//fs.close = function(fd, callback)fs.open(data/opencolse1.txt,'w',function(err,fd) { if (!err) { fs.close(fd,function(){ console.log(closed); }); }});
其中的flags其他语言也会有.其实主要分3部分 r、w、a.和c中的差不多。
1.r —— 以只读方式打开文件,数据流的初始位置在文件开始
2.r+ —— 以可读写方式打开文件,数据流的初始位置在文件开始
3.w ——如果文件存在,则将文件长度清0,即该文件内容会丢失。如果不存在,则尝试创建它。数据流的初始位置在文件开始
4.w+ —— 以可读写方式打开文件,如果文件不存在,则尝试创建它,如果文件存在,则将文件长度清0,即该文件内容会丢失。数据流的初始位置在文件开始
5.a —— 以只写方式打开文件,如果文件不存在,则尝试创建它,数据流的初始位置在文件末尾,随后的每次写操作都会将数据追加到文件后面。
6.a+ ——以可读写方式打开文件,如果文件不存在,则尝试创建它,数据流的初始位置在文件末尾,随后的每次写操作都会将数据追加到文件后面。
二、读写
1.简单文件读写
/** * created by administrator on 2016/3/21. */var fs = require('fs');var config = { maxfiles: 20, maxconnections: 15, rootpath: /webroot};var configtxt = json.stringify(config);var options = {encoding:'utf8', flag:'w'};//options 定义字符串编码 打开文件使用的模式 标志的encoding、mode、flag属性 可选//异步//fs.writefile = function(path, data, options, callback_)//同步//fs.writefilesync = function(path, data, options)fs.writefile('data/config.txt', configtxt, options, function(err){ if (err){ console.log(config write failed.); } else { console.log(config saved.); readfile(); }});function readfile(){ var fs = require('fs'); var options = {encoding:'utf8', flag:'r'}; //异步 //fs.readfile = function(path, options, callback_) //同步 //fs.readfilesync = function(path, options) fs.readfile('data/config.txt', options, function(err, data){ if (err){ console.log(failed to open config file.); } else { console.log(config loaded.); var config = json.parse(data); console.log(max files: + config.maxfiles); console.log(max connections: + config.maxconnections); console.log(root path: + config.rootpath); } });}
c:\program files (x86)\jetbrains\webstorm 11.0.3\bin\runnerw.exe f:\nodejs\node.exe simplereadwrite.jsconfig saved.config loaded.max files: 20max connections: 15root path: /webrootprocess finished with exit code 0
2.同步读写
/** * created by administrator on 2016/3/21. */var fs = require('fs');var veggietray = ['carrots', 'celery', 'olives'];fd = fs.opensync('data/veggie.txt', 'w');while (veggietray.length){ veggie = veggietray.pop() + ; //系统api //fd 文件描述 第二个参数是被写入的string或buffer // offset是第二个参数开始读的索引 null是表示当前索引 //length 写入的字节数 null一直写到数据缓冲区末尾 //position 指定在文件中开始写入的位置 null 文件当前位置 // fs.writesync(fd, buffer, offset, length[, position]); // fs.writesync(fd, string[, position[, encoding]]); //fs.writesync = function(fd, buffer, offset, length, position) var bytes = fs.writesync(fd, veggie, null, null); console.log(wrote %s %dbytes, veggie, bytes);}fs.closesync(fd);var fs = require('fs');fd = fs.opensync('data/veggie.txt', 'r');var veggies = ;do { var buf = new buffer(5); buf.fill(); //fs.readsync = function(fd, buffer, offset, length, position) var bytes = fs.readsync(fd, buf, null, 5); console.log(read %dbytes, bytes); veggies += buf.tostring();} while (bytes > 0);fs.closesync(fd);console.log(veggies: + veggies);
c:\program files (x86)\jetbrains\webstorm 11.0.3\bin\runnerw.exe f:\nodejs\node.exe syncreadwrite.jswrote olives 7byteswrote celery 7byteswrote carrots 8bytesread 5bytesread 5bytesread 5bytesread 5bytesread 2bytesread 0bytesveggies: olives celery carrots process finished with exit code 0
3.异步读写 和同步读写的参数差不多就是多了callback
/** * created by administrator on 2016/3/21. */var fs = require('fs');var fruitbowl = ['apple', 'orange', 'banana', 'grapes'];function writefruit(fd){ if (fruitbowl.length){ var fruit = fruitbowl.pop() + ; // fs.write(fd, buffer, offset, length[, position], callback); // fs.write(fd, string[, position[, encoding]], callback); // fs.write = function(fd, buffer, offset, length, position, callback) fs.write(fd, fruit, null, null, function(err, bytes){ if (err){ console.log(file write failed.); } else { console.log(wrote: %s %dbytes, fruit, bytes); writefruit(fd); } }); } else { fs.close(fd); ayncread(); }}fs.open('data/fruit.txt', 'w', function(err, fd){ writefruit(fd);});function ayncread(){ var fs = require('fs'); function readfruit(fd, fruits){ var buf = new buffer(5); buf.fill(); //fs.read = function(fd, buffer, offset, length, position, callback) fs.read(fd, buf, 0, 5, null, function(err, bytes, data){ if ( bytes > 0) { console.log(read %dbytes, bytes); fruits += data; readfruit(fd, fruits); } else { fs.close(fd); console.log (fruits: %s, fruits); } }); } fs.open('data/fruit.txt', 'r', function(err, fd){ readfruit(fd, ); });}
c:\program files (x86)\jetbrains\webstorm 11.0.3\bin\runnerw.exe f:\nodejs\node.exe asyncreadwrite.jswrote: grapes 7byteswrote: banana 7byteswrote: orange 7byteswrote: apple 6bytesread 5bytesread 5bytesread 5bytesread 5bytesread 5bytesread 2bytesfruits: grapes banana orange apple process finished with exit code 0
4.流式读写
/** * created by administrator on 2016/3/21. */var fs = require('fs');var grains = ['wheat', 'rice', 'oats'];var options = { encoding: 'utf8', flag: 'w' };//从下面的系统api可以看到 createwritestream 就是创建了一个writable流//fs.createwritestream = function(path, options) {// return new writestream(path, options);//};////util.inherits(writestream, writable);//fs.writestream = writestream;//function writestream(path, options)var filewritestream = fs.createwritestream(data/grains.txt, options);filewritestream.on(close, function(){ console.log(file closed.); //流式读 streamread();});while (grains.length){ var data = grains.pop() + ; filewritestream.write(data); console.log(wrote: %s, data);}filewritestream.end();//流式读function streamread(){ var fs = require('fs'); var options = { encoding: 'utf8', flag: 'r' }; //fs.createreadstream = function(path, options) { // return new readstream(path, options); //}; // //util.inherits(readstream, readable); //fs.readstream = readstream; // //function readstream(path, options) //createreadstream 就是创建了一个readable流 var filereadstream = fs.createreadstream(data/grains.txt, options); filereadstream.on('data', function(chunk) { console.log('grains: %s', chunk); console.log('read %d bytes of data.', chunk.length); }); filereadstream.on(close, function(){ console.log(file closed.); });}
c:\program files (x86)\jetbrains\webstorm 11.0.3\bin\runnerw.exe f:\nodejs\node.exe streamreadwrite.jswrote: oats wrote: rice wrote: wheat file closed.grains: oats rice wheat read 16 bytes of data.file closed.process finished with exit code 0
个人觉得像这些api用一用感受一下就ok了,遇到了会用就行了。