0

因此,在使用以下代码检查是否存在任何 .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");
});
4

1 回答 1

0

我假设,基于 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
  });
});
于 2020-10-06T06:05:09.740 回答