node的fs模塊
node的file system模塊提供的api有同步和異步兩種模式(大多數情況下都是用的異步方法,畢竟異步是node的特色,至於提供同步方法,可能應用程序復雜的時候有些場景使用同步會比較合適)。異步方法裏回調函數的第一個參數往往是個err對象,最後一個參數是返回的操作結果。
node裏面有很多模塊,不少模塊裏面又有很多api,沒必要短時間內一個個讀完,因此只需要記住每個模塊中最常用的一些api就好了。
*在使用同步模式的api時,error是即時拋出的,因此同步方法最好放在一個try{}catch{}塊中。
*在使用異步模式的api時,如果一組任務之間是有先後次序的,要註意把下一個任務嵌在上一個任務的callback中。
*對文件讀寫時,可以使用相對路徑,不過這個相對路徑是相對於process.cwd()的。
Class: fs.ReadStream/fs.WriteStream:
.open()
.close()
.path
.bytesRead
--------------------------------------
Class: fs.Stats: fs.stat()
, fs.lstat()
and fs.fstat()的返回對象。
stats.isFile()
stats.isDirectory()
stats.isBlockDevice()
stats.isCharacterDevice()
stats.isSymbolicLink() (only valid with fs.lstat())
stats.isFIFO()
stats.isSocket()
--------------------------------------
fs.access(path[, mode], callback):
用於檢測用戶對path中的文件/文件夾的權限;其中mode有下面四個值:
fs.constants.F_OK 對調用該方法的進程可見
fs.constants.R_OK 可讀
fs.constants.W_OK 可寫
fs.constants.X_OK 可執行
文檔不推薦在fs.open(), fs.readFile() or fs.writeFile()方法前使用access方法,推薦直接使用open/read/write即可。access方法應該在不直接使用path路徑下的文件的時候調用。
--------------------------------------
fs.appendFile(file, data[, options], callback):給文檔追加數據
1 fs.appendFile(‘message.txt‘, ‘data to append‘, (err) => { 2 if (err) throw err; 3 console.log(‘The "data to append" was appended to file!‘); 4 });
data:可以是字符|buffer
option:obj|string:為obj時候可設置的參數有:encoding
、mode
、flag;為string時則指定編碼格式如‘utf-8’
-------------------------------------
fs.createReadStream(path[, options]):返回一個readStream實例
option是如下的默認對象,如果opton是字符串,則只是指定編碼格式:
1 const defaults = { 2 flags: ‘r‘, 3 encoding: null, 4 fd: null, 5 mode: 0o666, 6 autoClose: true 7 };
*如果指定了fd,則path參數會被忽略;open事件也不會被觸發。Note that fd should be blocking; non-blocking fds should be passed to net.Socket.
-----------------------------
fs.createWriteStream(path[, options]):參考createReadStream
-----------------------------------
fs.exists(path, callback):判斷路徑中的文件/文件夾是否存在
1 fs.exists(‘/etc/passwd‘, (exists) => { 2 console.log(exists ? ‘it\‘s there‘ : ‘no passwd!‘); 3 });
文檔推薦使用.access()而不是.exists(),因為access的回調裏有err參數,而exists只是返回一個布爾值。另外也不推薦在.open/write/read文件之前使用exists方法檢測。
RECOMMENDED:
1 fs.open(‘myfile‘, ‘wx‘, (err, fd) => { 2 if (err) { 3 if (err.code === ‘EEXIST‘) { 4 console.error(‘myfile already exists‘); 5 return; 6 } 7 throw err; 8 } 9 writeMyData(fd); 10 });
1 fs.open(‘myfile‘, ‘r‘, (err, fd) => { 2 if (err) { 3 if (err.code === ‘ENOENT‘) { 4 console.error(‘myfile does not exist‘); 5 return; 6 } 7 throw err; 8 } 9 readMyData(fd); 10 });
後面還有好幾十個方法。。。罷了罷了先停一下。
node的fs模塊