最新文檔請查看倉庫 https://github.com/wangduandu...html
同步
和異步
的兩種方式,本筆記只記錄異步的APInull
或者undefinded
。try catch
捕獲異常沒法保證順序
的。最好將一個函數放在另外一個函數的回調函數中去執行。這種回調的嵌套層次一旦過深,就會形成回調地獄
很是不建議使用同步
的fs方法,由於同步的方法會阻斷其餘事情,直到fs方法完成。filepaths目前支持4中node
string
Buffer
URL Object
file:
開頭的協議process.cwd()
獲取當前工做路徑。內存泄露
或者程序崩潰
Hello World
, 若是在寫入'Aloha',那麼文件的內容是Aloha World
,而不是'Aloha'.fs全部的api,除了那些同步的api和fs.FSWatcher(), 基本上都使用libuv的線程池。在有些應用程序上,這個可能致使很是糟糕的性能表現。libuv的線程池有固定的大小,默認只有4個,能夠經過設置環境變量UV_THREADPOOL_SIZE
去增長libuv的線程的數量。git
fs.readdir()
或者fs.readdirSync()
被調用,而且參數withFileTypes
是true
, 那麼返回結果就是fs.Dirent objects
, 而不是strings
or Buffers
dirent方法github
來自 fs.watch()
windows
Eventapi
change
close
error
注意:某些系統可能不會返回filename。若是encoding參數是buffer,那麼文件名是以buffer的形式返回,默認文件名是utf-8格式的字符串。app
fs.watch('./tmp', { encoding: 'buffer' }, (eventType, filename) => { if (filename) { console.log(filename); // Prints: <Buffer ...> } });
來自fs.createReadStream()
異步
Event函數
close
open
ready
第一次觸發是在open事件以後來自 fs.stat()
, fs.lstat()
and fs.fstat()
以及他們的同步版本。性能
Stats { dev: 2114, ino: 48064969, mode: 33188, nlink: 1, uid: 85, gid: 100, rdev: 0, size: 527, blksize: 4096, blocks: 8, atimeMs: 1318289051000.1, mtimeMs: 1318289051000.1, ctimeMs: 1318289051000.1, birthtimeMs: 1318289051000.1, atime: Mon, 10 Oct 2011 23:24:11 GMT, mtime: Mon, 10 Oct 2011 23:24:11 GMT, ctime: Mon, 10 Oct 2011 23:24:11 GMT, birthtime: Mon, 10 Oct 2011 23:24:11 GMT }
Event
測試
訪問權限測試
fs.access(path[, mode], callback) 測試是否能夠訪問某個路徑。不建議fs.open(), fs.readFile() or fs.writeFile()調用前,調用fs.access去檢查測試路徑是否存在
fs.exists(path, callback), 不建議fs.open(), fs.readFile() or fs.writeFile()調用前,調用fs.exists去檢測文件是否存在流操做
建立可讀流
fs.createReadStream(path[, options])建立可寫流
fs.createWriteStream(path[, options])文件夾操做
建立文件夾
fs.mkdir(path[, options], callback)刪除目錄
fs.rmdir(path, callback)建立臨時文件夾
fs.mkdtemp(prefix[, options], callback)讀取文件夾
fs.readdir(path[, options], callback)文件操做
打開文件
fs.open(path[, flags[, mode]], callback)讀取文件
fs.read(fd, buffer, offset, length, position, callback)讀取文件
fs.readFile(path[, options], callback)重命名文件
fs.rename(oldPath, newPath, callback)讀取文件信息
fs.stat(path[, options], callback)刪除文件
fs.unlink(path, callback)中止監控文件
fs.unwatchFile(filename[, listener])修改時間
fs.utimes(path, atime, mtime, callback)監控文件變化
fs.watch(filename, options)關閉文件
fs.close(fd, callback)追加文件
fs.appendFile(path, data[, options], callback)改變文件模式
fs.chmod(path, mode, callback)改變文件所屬
fs.chown(path, uid, gid, callback)複製文件
fs.copyFile(fs.copyFile(src, dest[, flags], callback))寫文件
fs.write(fd, buffer[, offset[, length[, position]]], callback)寫文件
fs.write(fd, string[, position[, encoding]], callback)寫文件
fs.writeFile(file, data[, options], callback)其餘
fs常量
fs.constants注意事項
fs.watch
並非百分百跨平臺。例如它的recursive
參數僅支持macOS和windows。fs.watch的底層通知機制在不一樣平臺上的實現是不一樣的,若是底層不支持某個特性,那麼fs.watch也是不能支持的。另外回調函數中的filename參數,也是不保證必定存在。fs.watch()
比fs.watchFile()
更高效,可能的話,儘可能使用前者。