我假设,基于 chokidars 文档,它用于监视目录中的文件更改?
如果要在节点 js 中打开文件,只需使用文件系统 ('fs') 模块。
const fs = require('fs')
//open file synchronously
let file;
try {
file = fs.readFile(/* provide path to file */)
} catch(e) {
// if file not existent
file = {}
console.log(e)
}
//asynchronously
fs.readFile(/* file path */, (err, data) => {
if (err) throw err;
// do stuff with data
});
编辑:作为额外的一点,您可以为 fs 启用 async/await
const fs = require('fs')
const { promisify } = require('util')
const readFileAsync = promisify(fs.readFile);
(async function() {
try {
const file = await readFileAsync(/* file path */)
} catch(e) {
// handle error if file does not exist...
}
})();
如果你想在添加文件时打开文件,你可以这样做
const fs = require('fs')
var fileWatcher = require("chokidar");
var watcher = fileWatcher.watch("./*.xml", {
ignored: /[\/\\]\./,
usePolling: true,
persistent: true,
});
// Add event listeners.
watcher.on("add", function (path) {
console.log("File", path, "has been added");
fs.readFile(path, (err, data) => {
if (err) throw err;
// do stuff with data
});
});