最新文档请查看仓库 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()
更高效,可能的话,尽可能使用前者。