Node.js文件操作方法汇总

2020-06-18 05:55:54易采站长站整理

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)JetBrainsWebStorm 11.0.3binrunnerw.exe" F:nodejsnode.exe SimpleReadWrite.js
Config Saved.
Config Loaded.
Max Files: 20
Max Connections: 15
Root Path: /webroot

Process 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)JetBrainsWebStorm 11.0.3binrunnerw.exe" F:nodejsnode.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.异步读写 和同步读写的参数差不多就是多了callback

								 
			 
相关文章 大家在看