Node最引以为傲的就是它有一个非常小的核心。有一些语言绑定了完整的POSIX API,而 Node实现了尽可能少的绑定,并通过同步、异步或流API形式暴露他们。
这种方法意味着,操作系统中有一些非常方便的功能,需要在Node中重建。这是一个教你如何使用文件系统软件包的实用教程。
引用文件
与文件系统的交互很重要的一点是要指向正确的文件。由于NPM的包使用相对路径引用,所以你不能把路径写死在代码。有两个主要方式来以确保包能引用到正确的文件:
// 使用 `path.join()` 而不是 `+` 确保Windows也能正常工作const path = require("path")// 找到基于调用点的相对路径,对于命令行程序(CLI applications)非常实用path.join(process.cwd(), "my-dynamic-file")// 或者path.resolve("my-dynamic-file")// 基于一个文件找到另外一个文件path.join(__dirname, "my-package-file")
读取文件
在节点中的异步读取文件的最简单方法就是使用流!下面是一个例子:
const path = require("path")const fs = require("fs")// read a file and pipe it to the consolefs.createReadStream(path.join(__dirname, "my-file")) .pipe(process.stdout)
创建文件
创建文件也并不是很难,这里有一个用node实现的cat命令:
const path = require("path")const fs = require("fs")// cat ./my-file > ./my-other-filefs.createReadStream(path.join(__dirname, "my-file")) .pipe(fs.createWriteStream(path.join(__dirname, "./my-other-file")))
删除文件
在Shell脚本中删除的文件和目录通常使用 rm-rf 命令。NodeJS中一个 rimraf 也实现了相同的功能:
const rimraf = require("rimraf")const path = require("path")rimraf(path.join(__dirname, "./my-directory"), err => { if (err) throw err})
创建目录
创建跟删除文件很相似,使用 mkdirp 包
const mkdirp = require("mkdirp")const path = require("path")mkdirp(path.join(__dirname, "foo/bar"), err => { if (err) throw err})查找文件
使用 readdirp 查找当前目录下的文件:
const readdirp = require("readdirp")const json = require("JSONStream")const path = require("path")// recursively print out all files in all subdirectories// to the command line. The object stream must be// stringified before being passed to `stdout`.readdirp({ root: path.join(__dirname) }) .pipe(json.stringify()) .pipe(process.stdout)使用findup查找当前父级目录中的文件:
const findup = require("findup")const path = require("path")// recurse up all files relative to __dirname and find// all `package.json` files.findup(path.join(__dirname), "package.json", (err, res) => { if (err) throw err console.log("dir is: " + res)})关于管道(pipes)在管道中对整个数据流的错误进行一次处理非常。而不用对每个单独的数据流使用 .on("error", cb) :
const pump = require("pump")const fs = require("fs")// oh no, no errors are handled!fs.createReadStream("./in.file").pipe(fs.createWriteStream("./out.file"))// that"s better, we"re handing errors nowconst rs = fs.createReadStream("./in.file")const ws = fs.createWriteStream("./out.file")pump(rs, ws, err => { if (err) throw err})