Reputation: 1680
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:
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:
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.
Upvotes: 2
Views: 6371
Reputation: 354
Haven't used golb.Hope this will help you.
var fs=require('fs');
var pattern=RegExp('.md$');//Enter file extension here
fs.readdir('..//',(err,files)=>{
//console.log(files);
if(files.find((file)=>{return pattern.test(file)==true;})){
//console.log('file found'); your code
}
else{
//console.log('file not found'); your code
}
});
Upvotes: 1
Reputation: 181278
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.
Upvotes: 4
Reputation: 637
Try this.
const path = require('path');
const glob = require('glob');
glob(
'*.sln',
{ cwd: path.resolve(process.cwd(), '..') }, // you want to search in parent directory
(err, files) => {
if (err) {
throw err;
}
if (files.length) {
// File exists. All matched filenames are inside files array.
} else {
// File does not exist. files array is empty.
}
}
);
glob
is an asynchronous function so results are provided in a callback and not returned synchronously.
You can also test you glob expressions using globster.xyz
Upvotes: 1