Search code examples
javascriptnode.jsnode-modulesglob

Use glob node.js to know if a file exists in the parent folder using wildcard


I need to search in the parent folder of where a node.js yeoman generator script is running to see if a file exists, but I won't know the file name - only the extension.

Glob: https://www.npmjs.com/package/glob

Folder Structure:

  • C:\Work\
  • C:\Work\Company\
  • C:\Work\Company\Project\

Assume that the Project folder is where the command prompt is... I want to run a Yeoman generator that looks into the Company folder first to see if a specific file exists. It could be any file name, ending in .sln.

There are plenty of beginner resources, but I can't find any examples that show:

  1. How to look in the parent folder successfully; and
  2. How to work with the output (true/false?) to use in a variable for logic later in the function.

Here's what I tried to do, but I am admittedly much more adept in C# than I am in JS.

var globbed = glob("../*.sln", function(err, files){
    this.log(chalk.yellow("err = " + err));
    this.log(chalk.yellow("files = " + files));
});

and this...

var gOptions = { cwd: "../" };
var globbed = glob("*.sln", gOptions, function(err, files){
    this.log(chalk.yellow("err = " + err));
    this.log(chalk.yellow("files = " + files));
});

In both examples, globbed is an object, but I don't know what its properties are, and I am not able to access the internal function.

Essentially, I need to know if the file exists so that I can run an If/Then statement on it.


Solution

  • Use glob.sync:

    const files = glob.sync("*.sln", { cwd: "../" }); 
    

    or simply

    const files = glob.sync("../*.sln"); 
    

    files will be an array of *.sln files, if any, in the parent directory. Obviously, glob.sync is synchronous.