Node.js, seperti bahasa lain, juga mempunyai operasi fail. Jangan bercakap tentang operasi fail dalam node.js Operasi fail dalam bahasa lain biasanya termasuk membuka, menutup, membaca, menulis, maklumat fail, mencipta dan memadam direktori, memadam fail, mengesan laluan fail, dsb. Perkara yang sama berlaku dalam node.js Mereka juga mempunyai fungsi ini. Mungkin API berbeza daripada bahasa lain.
1. Pembukaan dan penutup segerak dan tak segerak
/** * 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"); }); } });
Bendera juga terdapat dalam bahasa lain Malah, ia terbahagi kepada tiga bahagian: r, w, dan a.
1.r - Buka fail dalam mod baca sahaja, kedudukan awal aliran data adalah pada permulaan fail
2.r+ - Buka fail dalam mod baca-tulis, kedudukan awal aliran data adalah pada permulaan fail
3.w - Jika fail wujud, panjang fail akan dikosongkan kepada 0, iaitu kandungan fail akan hilang. Jika ia tidak wujud, cuba ciptakannya. Kedudukan awal aliran data adalah pada permulaan fail
4.w+ - Buka fail dalam mod baca-tulis Jika fail tidak wujud, cuba buatnya Jika fail wujud, tetapkan panjang fail kepada 0, iaitu kandungan fail akan hilang. Kedudukan awal aliran data adalah pada permulaan fail
5.a - Buka fail dalam mod tulis sahaja Jika fail itu tidak wujud, cuba buatnya Kedudukan awal aliran data adalah di hujung fail hujung fail.
6.a+ - Buka fail untuk membaca dan menulis Jika fail tidak wujud, cuba buatnya Kedudukan awal aliran data adalah di hujung fail fail tersebut.
2. Membaca dan Menulis
1. Membaca dan menulis fail ringkas
/** * 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.js Config Saved. Config Loaded. Max Files: 20 Max Connections: 15 Root Path: /webroot Process finished with exit code 0
2. Membaca dan menulis serentak
/** * 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.js Wrote olives 7bytes Wrote celery 7bytes Wrote carrots 8bytes read 5bytes read 5bytes read 5bytes read 5bytes read 2bytes read 0bytes Veggies: olives celery carrots Process finished with exit code 0
3. Membaca dan menulis tak segerak dan membaca dan menulis segerak hampir mempunyai lebih banyak parameter panggil balik
/** * 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.js Wrote: grapes 7bytes Wrote: banana 7bytes Wrote: orange 7bytes Wrote: apple 6bytes read 5bytes read 5bytes read 5bytes read 5bytes read 5bytes read 2bytes Fruits: grapes banana orange apple Process finished with exit code 0
4. Menstrim membaca dan menulis
/** * 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.js Wrote: oats Wrote: rice Wrote: wheat File Closed. Grains: oats rice wheat Read 16 bytes of data. File Closed. Process finished with exit code 0
Secara peribadi, saya rasa API ini akan menjadi ok sebaik sahaja anda menggunakannya dan merasainya, dan anda hanya perlu boleh menggunakannya apabila anda menemuinya.