文件读取
Node.js 文件读写
推荐使用 node-fs-extra 来扩展原生的
读取为流
读取文件并将其输出到
const fs = require("fs");
const readStream = fs.createReadStream("myfile.txt");
readStream.pipe(process.stdout);
创建一个文件的
const crypto = require("crypto");
const fs = require("fs");
const readStream = fs.createReadStream("myfile.txt");
const hash = crypto.createHash("sha1");
readStream
.on("data", function (chunk) {
hash.update(chunk);
})
.on("end", function () {
console.log(hash.digest("hex"));
});
const crypto = require("crypto");
const fs = require("fs");
const readStream = fs.createReadStream("myfile.txt");
const hash = crypto.createHash("sha1");
readStream
.on("readable", function () {
const chunk;
while (null !== (chunk = readStream.read())) {
hash.update(chunk);
}
})
.on("end", function () {
console.log(hash.digest("hex"));
});
文本读取
const { promisify } = require("util");
const fs = require("fs");
const readFileAsync = promisify(fs.readFile); // (A)
const filePath = process.argv[2];
readFileAsync(filePath, { encoding: "utf8" })
.then((text) => {
console.log("CONTENT:", text);
})
.catch((err) => {
console.log("ERROR:", err);
});
如果文件不存在的话则会报错,有时候我们需要首先判断文件是否存在:
fs.exists(path, callback);
fs.existsSync(path);
JSON
const fs = require("fs-extra");
const file = "/tmp/this/path/does/not/exist/file.json";
fs.outputJson(file, { name: "JP" }, (err) => {
console.log(err); // => null
fs.readJson(file, (err, data) => {
if (err) return console.error(err);
console.log(data.name); // => JP
});
});
// With Promises:
fs.outputJson(file, { name: "JP" })
.then(() => fs.readJson(file))
.then((data) => {
console.log(data.name); // => JP
})
.catch((err) => {
console.error(err);
});
function processFile(inputFile) {
const fs = require("fs"),
readline = require("readline"),
instream = fs.createReadStream(inputFile),
outstream = new (require("stream"))(),
rl = readline.createInterface(instream, outstream);
rl.on("line", function (line) {
console.log(line);
});
rl.on("close", function (line) {
console.log(line);
console.log("done reading file.");
});
}
processFile("/path/to/a/input/file.txt");
fs.readFile("input.txt", "utf8", function (err, data) {
if (err) throw err;
console.log(data);
});