【问题标题】:Access file after checking if available in folder检查文件夹中是否可用后访问文件
【发布时间】:2020-10-06 01:42:10
【问题描述】:

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

【问题讨论】:

    标签: node.js filestream chokidar


    【解决方案1】:

    根据 chokidars 文档,我假设它用于监视目录中的文件更改?

    如果你想在 node 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
      });
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-14
      • 2010-11-08
      • 2011-02-12
      相关资源
      最近更新 更多