**********文件操作模塊,可以完全代替操作系統(tǒng)命令************
1.****nodejs文件操作分為同步和異步請(qǐng)求岩喷。同步后面加了Sync
//異步刪除
fs.unlink('/tmp/hello', (err) => {
if (err) throw err;
console.log('successfully deleted /tmp/hello');
});
//同步刪除
fs.unlinkSync('/tmp/hello');
console.log('successfully deleted /tmp/hello');
2.**異步不保證順序
fs.rename('/tmp/hello', '/tmp/world', (err) => {
if (err) throw err;
console.log('renamed complete');
});
fs.stat('/tmp/world', (err, stats) => {
if (err) throw err;
console.log(`stats: ${JSON.stringify(stats)}`);
//stats: {"dev":-593730986,"mode":33206,"nlink":1,"uid":0,"gid":0,
//"rdev":0,"ino":2251799813714667,"size":3,"atime":"2016-03-25T07:41:15.892Z",
//"mtime":"2016-03-25T07:41:19.870Z","ctime":"2016-03-25T07:42:00.065Z",
//"birthtime":"2016-03-25T07:41:15.819Z"}
});
//下面可以保證
fs.rename('/tmp/hello', '/tmp/world', (err) => {
if (err) throw err;
fs.stat('/tmp/world', (err, stats) => {
if (err) throw err;
console.log(`stats: ${JSON.stringify(stats)}`);
});
});
4.Class: fs.FSWatcher 類(lèi)售碳, 從fs.watch()方法返回
(1)Event: 'change'
event <String> 文件類(lèi)型改變
filename <String> 文件名改變
(2)Event: 'error'
(3)watcher.close() 停止監(jiān)聽(tīng)文件變化
5.Class: fs.ReadStream 類(lèi)
(1)Event: 'open' fd <Number> 整數(shù)文件描述符
當(dāng)ReadStream文件打開(kāi)時(shí)觸發(fā)
(2)readStream.path 打開(kāi)文件的路徑
6.***Class: fs.Stats 類(lèi)
(1)對(duì)象從fs.stat(), fs.lstat()强重、 fs.fstat()
stats.isFile()
stats.isDirectory()
stats.isBlockDevice()
stats.isCharacterDevice()
stats.isSymbolicLink() (only valid with fs.lstat())
stats.isFIFO()
stats.isSocket()
//例子
fs.stat('input.txt', function (err, stats) {
if (err) {
return console.error(err);
}
console.log(stats);
console.log("讀取文件信息成功绞呈!");
// 檢測(cè)文件類(lèi)型
console.log("是否為文件(isFile) ? " + stats.isFile());
console.log("是否為目錄(isDirectory) ? " + stats.isDirectory());
});
(2)對(duì)于普通文件 util.inspect(stats)會(huì)返回
{
dev: 2114,
ino: 48064969,
mode: 33188,
nlink: 1,
uid: 85,
gid: 100,
rdev: 0,
size: 527,
blksize: 4096,
blocks: 8,
atime: Mon, 10 Oct 2011 23:24:11 GMT, //Access Time"
mtime: Mon, 10 Oct 2011 23:24:11 GMT, //Modified Time 數(shù)據(jù)改變
ctime: Mon, 10 Oct 2011 23:24:11 GMT, //Change Time status 改變
birthtime: Mon, 10 Oct 2011 23:24:11 GMT //創(chuàng)建日期
}
7.Class: fs.WriteStream 文件寫(xiě)入流
(1)Event: 'open' fd <Number> 整數(shù)文件描述符
當(dāng)WriteStream文件打開(kāi)時(shí)觸發(fā)
(2)writeStream.bytesWritten 當(dāng)現(xiàn)在為止已經(jīng)寫(xiě)入的文件大小
(3)writeStream.path 寫(xiě)入的路徑
8.fs.access(path[, mode], callback)
(1)mode類(lèi)型
fs.F_OK - 確定文件是否存在,默認(rèn)间景,沒(méi)有rwx權(quán)限
fs.R_OK - 文件可讀
fs.W_OK - 文件可寫(xiě)
fs.X_OK - 文件可執(zhí)行 對(duì)于 Windows 沒(méi)作用(will behave like fs.F_OK).
(2)例子
fs.access('/etc/passwd', fs.R_OK | fs.W_OK, (err) => {
console.log(err ? 'no access!' : 'can read/write');
});
(3)同步佃声,失敗會(huì)拋出異常
fs.accessSync(path[, mode])
9.***fs.appendFile(file, data[, options], callback) 添加文件
(1)參數(shù)
file <String> | <Number> filename 或者 file descriptor
data <String> | <Buffer> 數(shù)據(jù)
options <Object> | <String>
encoding <String> | <Null> default = 'utf8'
mode <Number> default = 0o666
flag <String> default = 'a'
callback <Function>
(2)例子
fs.appendFile('message.txt', 'data to append','utf8', (err) => {
if (err) throw err;
console.log('The "data to append" was appended to file!');
});
(3)同步版本
fs.appendFileSync(file, data[, options])
10.幾個(gè)函數(shù)?倘要?圾亏??
fs.chmod(path, mode, callback)
fs.chmodSync(path, mode)
fs.chown(path, uid, gid, callback)#
fs.chownSync(path, uid, gid)#
11.***關(guān)閉文件
fs.close(fd, callback)
fs.closeSync(fd)
//例子
var buf = new Buffer(1024);
console.log("準(zhǔn)備打開(kāi)文件封拧!");
fs.open('input.txt', 'r+', function(err, fd) {
if (err) {
return console.error(err);
}
console.log("文件打開(kāi)成功志鹃!");
console.log("準(zhǔn)備讀取文件!");
fs.read(fd, buf, 0, buf.length, 0, function(err, bytes){
if (err){
console.log(err);
}
// 僅輸出讀取的字節(jié)
if(bytes > 0){
console.log(buf.slice(0, bytes).toString());
}
// 關(guān)閉文件
fs.close(fd, function(err){
if (err){
console.log(err);
}
console.log("文件關(guān)閉成功");
});
});
});
12.****fs.createReadStream(path[, options]) 返回ReadStream對(duì)象
(1)options
{
flags: 'r',
encoding: null,
fd: null, //若為非空哮缺,則忽略path弄跌,使用文件描述符,不會(huì)有open事件
mode: 0o666,
autoClose: true, //若為false則不會(huì)自動(dòng)關(guān)閉
start:Number, //字節(jié)開(kāi)始
end:Number//字節(jié)結(jié)束
}
(2)fs.createReadStream('sample.txt', {start: 90, end: 99});
(3)源代碼
fs.createReadStream = function(path, options) {
return new ReadStream(path, options);
};
13.****fs.createWriteStream(path[, options]) 返回WriteStream
(1)
{
flags: 'w',
defaultEncoding: 'utf8',
fd: null,
mode: 0o666,
autoClose: true
}
(2)源代碼底層實(shí)現(xiàn)
fs.createWriteStream = function(path, options) {
return new WriteStream(path, options);
};
(3)例子********
var fs = require('fs'),
path = require('path'),
out = process.stdout;
var filePath = 'x264-BATV.mkv';
var readStream = fs.createReadStream(filePath);
var writeStream = fs.createWriteStream('file.mkv');
var stat = fs.statSync(filePath);
var totalSize = stat.size;
var passedLength = 0;
var lastSize = 0;
var startTime = Date.now();
readStream.on('data', function(chunk) {
passedLength += chunk.length;//獲得已經(jīng)復(fù)制的大小
if (writeStream.write(chunk) === false) {
readStream.pause();
}
});
readStream.on('end', function() {
writeStream.end();
});
writeStream.on('drain', function() {
readStream.resume();
});
setTimeout(function show() {
var percent = Math.ceil((passedLength / totalSize) * 100);
var size = Math.ceil(passedLength / 1000000);
var diff = size - lastSize;
lastSize = size;
out.clearLine();
out.cursorTo(0);
out.write('已完成' + size + 'MB, ' + percent + '%, 速度:' + diff * 2 + 'MB/s');
if (passedLength < totalSize) {
setTimeout(show, 500);
} else {
var endTime = Date.now();
console.log();
console.log('共用時(shí):' + (endTime - startTime) / 1000 + '秒。');
}
}, 500);
14.***創(chuàng)建目錄
fs.mkdir(path[, mode], callback) mode默認(rèn)0o777
fs.mkdirSync(path[, mode])
//目錄操作
fs.mkdir('/tmp/test',function(err){
if (err) {
return console.error(err);
}
console.log("目錄創(chuàng)建成功尝苇。");
});
15.**fs.open(path, flags[, mode], callback) 打開(kāi)文件
(1)flags
'r' - 讀模式.文件不存在報(bào)異常
'r+' - 讀寫(xiě).文件不存在報(bào)異常
'rs' 同步讀铛只,跳過(guò)緩沖區(qū) 要同步用fs.openSync()
'rs+' 同步讀寫(xiě)
'w' - 寫(xiě)模式. 文件不存在創(chuàng)建
'wx' - 寫(xiě)模式. 路徑存在則失敗
'w+' - 讀寫(xiě)模式. 文件不存在創(chuàng)建
'wx+' - 讀寫(xiě)模式. 路徑存在則失敗
'a' - 添加. 文件不存在創(chuàng)建
'ax' - 添加. 文件不存在失敗
'a+' - 讀添加. 文件不存在創(chuàng)建
'ax+' - 讀添加. 文件不存在失敗
(2)mode 默認(rèn)0666 可讀寫(xiě)
(3)回調(diào)函數(shù)包含兩個(gè)參數(shù) (err, fd)
(4)fs.openSync(path, flags[, mode]) 同步方法
16.***fs.read(fd, buffer, offset, length, position, callback)
根據(jù)文件描述符fd來(lái)讀取文件,回調(diào)(err, bytesRead, buffer)
//例子
fs.open('input.txt', 'r+', function(err, fd) {
if (err) {
return console.error(err);
}
console.log("文件打開(kāi)成功糠溜!");
console.log("準(zhǔn)備讀取文件:");
fs.read(fd, buf, 0, buf.length, 0, function(err, bytes){
if (err){
console.log(err);
}
console.log(bytes + " 字節(jié)被讀取");
// 僅輸出讀取的字節(jié)
if(bytes > 0){
console.log(buf.slice(0, bytes).toString());
}
});
});
17.***fs.readdir(path, callback) 讀目錄
(1)回調(diào)(err, files)files是文件的目錄數(shù)組
(2)fs.readdirSync(path)同步方法
(3)例子
console.log("查看 /tmp 目錄");
fs.readdir("/tmp/",function(err, files){
if (err) {
return console.error(err);
}
files.forEach( function (file){
console.log( file );
});
});
18.***fs.readFile(file[, options], callback) 度文件
(1)
file <String> | <Integer> filename or file descriptor
options <Object> | <String>
encoding <String> | <Null> default = null
flag <String> default = 'r'
callback <Function>
(2)例子
fs.readFile('/etc/passwd', 'utf8'淳玩,(err, data) => {
if (err) throw err;
console.log(data);
});
(3)fs.readFileSync(file[, options])同步讀
返回文件的內(nèi)容,如果制定encoding則返回字符串非竿,否則返回buffer
var source = fs.readFileSync('/path/to/source', {encoding: 'utf8'});
fs.writeFileSync('/path/to/dest', source);
19. ***文件寫(xiě)操作
fs.rename(oldPath, newPath, callback) callback只有一個(gè)err
fs.renameSync(oldPath, newPath)
20.***刪除目錄
fs.rmdir(path, callback)callback只有一個(gè)err
fs.rmdirSync(path)#
//例子
console.log("準(zhǔn)備刪除目錄 /tmp/test");
fs.rmdir("/tmp/test",function(err){
if (err) {
return console.error(err);
}
console.log("讀取 /tmp 目錄");
fs.readdir("/tmp/",function(err, files){
if (err) {
return console.error(err);
}
files.forEach( function (file){
console.log( file );
});
});
});
21.***列出文件屬性
fs.stat(path, callback)# 兩個(gè)參數(shù)(err, stats)
fs.statSync(path) 返回fs.Stats.
20.***截取文件
fs.truncate(path, len, callback) == fs.ftruncate(path,len,callback)//截?cái)辔募? fs.truncateSync(path, len)
(1)例子
var fs = require("fs");
var buf = new Buffer(1024);
console.log("準(zhǔn)備打開(kāi)文件蜕着!");
fs.open('input.txt', 'r+', function(err, fd) {
if (err) {
return console.error(err);
}
console.log("文件打開(kāi)成功!");
console.log("截取10字節(jié)后的文件內(nèi)容红柱。");
// 截取文件
fs.ftruncate(fd, 10, function(err){
if (err){
console.log(err);
}
console.log("文件截取成功承匣。");
console.log("讀取相同的文件");
fs.read(fd, buf, 0, buf.length, 0, function(err, bytes){
if (err){
console.log(err);
}
// 僅輸出讀取的字節(jié)
if(bytes > 0){
console.log(buf.slice(0, bytes).toString());
}
// 關(guān)閉文件
fs.close(fd, function(err){
if (err){
console.log(err);
}
console.log("文件關(guān)閉成功!");
});
});
});
});
21.***fs.unwatchFile(filename[, listener])
(1)停止監(jiān)聽(tīng)文件變化
fs.watch(filename[, options][, listener])
options:{ persistent: true, recursive: false }.
listener:(event, filename)
(2)例子
fs.watch('somedir', (event, filename) => {
console.log(`event is: ${event}`);
if (filename) {
console.log(`filename provided: ${filename}`);
} else {
console.log('filename not provided');
}
});
22.***fs.watchFile(filename[, options], listener)
//文檔中介紹原理是輪詢(xún)(每隔一個(gè)固定的時(shí)間去檢查文件是否改動(dòng))
(1)options:{ persistent: true, interval: 5007 }.
(2)例子
fs.watchFile('message.text', (curr, prev) => {
console.log(`the current mtime is: ${curr.mtime}`);
console.log(`the previous mtime was: ${prev.mtime}`);
});
//watch()這個(gè)方法是通過(guò)監(jiān)聽(tīng)操作系統(tǒng)提供的各種“事件”(內(nèi)核發(fā)布的消息)實(shí)現(xiàn)的
fs.watch() is more efficient than fs.watchFile
23.***寫(xiě)文件
(1)fs.write(fd, data[, position[, encoding]], callback)
(2)fs.writeFile(file, data[, options], callback)
(4)同步方法
fs.writeFileSync(file, data[, options])
fs.writeSync(fd, buffer, offset, length[, position])
fs.writeSync(fd, data[, position[, encoding]])
(5)例子,重寫(xiě)會(huì)覆蓋
fs.writeFile('input.txt', '我是通過(guò)寫(xiě)入的文件內(nèi)容锤悄!', function(err) {
if (err) {
return console.error(err);
}
console.log("數(shù)據(jù)寫(xiě)入成功韧骗!");
console.log("--------我是分割線(xiàn)-------------")
console.log("讀取寫(xiě)入的數(shù)據(jù)!");
fs.readFile('input.txt', function (err, data) {
if (err) {
return console.error(err);
}
console.log("異步讀取文件數(shù)據(jù): " + data.toString());
});
});