问题描述
因此,在使用以下代码检查是否存在任何.xml文件之后,如何访问该文件?我需要访问文件以解析内容并显示。
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");
});
解决方法
基于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启用异步/等待
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,data) => {
if (err) throw err;
// do stuff with data
});
});