Access file after checking if available in folder

269 views Asked by At

So after checking if any .xml files are present with the below code, how do I access the file? I need to access the file to parse the contents and display.

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");
});
1

There are 1 answers

0
uranshishko On

I'm assuming, based on chokidars docs that it's used to watch for file changes in a directory?

If you want to open a file in node js just use the filesystem ('fs') module.

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
});

EDIT: as a little extra you can enable async/await for 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...
  }
})();

if you want to open file when its added you could do this

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
  });
});