How to use the sync function from glob

Find comprehensive JavaScript glob.sync code examples handpicked from public code repositorys.

glob.sync is a function in Node.js used to search for files/directories based on a provided pattern synchronously.

230
231
232
233
234
235
236
237
238
239
/**
 * We do not need to ship the Electron binaries.
 */
function deleteElectronBinaries() {
    const preBuildsFolder = path.join(__dirname, 'node_modules', 'zeromqold', 'prebuilds');
    glob.sync('**/electron.napi.*.node', { sync: true, cwd: preBuildsFolder }).forEach((file) => {
        console.log(`Deleting ${file}`);
        fs.rmSync(path.join(preBuildsFolder, file), { force: true });
    });
}
fork icon209
star icon960
watch icon43

216
217
218
219
220
221
222
223
224
225
  .filter(function (path) { return path[0] == '!'; })
  .map(function (path) { return path.substring(1); });

return globPatterns.reduce(function (accumulator, path) {
  var expandedWithSource =
    glob.sync(path, { ignore: ignoredGlobPatterns, nodir: true, nonull: true })
    .map(function (expandedPath) { return { expanded: expandedPath, source: path }; });

  return accumulator.concat(expandedWithSource);
}, []);
fork icon23
star icon276
watch icon6

How does glob.sync work?

glob.sync is a function that returns an array of file paths that match a specified pattern, using synchronous filesystem methods to perform the search.

The pattern can use wildcards such as * and ? to match multiple characters or specify a range of characters, and can also include globstar ** to match directories recursively.

The function takes two arguments: the pattern to match and an optional object specifying options such as whether to include hidden files, ignore certain files or directories, and set the current working directory.

90
91
92
93
94
95
96
97
98
99
}

static resolves(vv) { // TODO make async and pass a cb
  // Return an array of resolved filenames, this can also expand `*` etc
  return [].concat(...vv.map(v => this.resolve(v)) // Handle ~ or . or ..
    .map(p => glob.sync(p))); // And expand * etc (to an array of arrays)
}

static firstExisting(arr) {
  // Find the first of arr that exists, args can be relative to the process directory .../dweb-mirror
fork icon20
star icon211
watch icon20

311
312
313
314
315
316
317
318
319
320
async afterBuild () {
  // Delete source map files once uploaded to sentry
  // Remove these lines if you need to serve source map in production.
  // Then you may need to adjust webpack devtool build option
  if (!ctx.dev && uploadSourceMapsToSentry) {
    const mapFiles = glob.sync('dist/**/*.map')
    await pMap(mapFiles, async (f) => {
      await deleteFile(path.join(__dirname, f))
    })
    // It seems we need to manually remove source map references in CSS files
fork icon56
star icon88
watch icon7

Ai Example

1
2
3
4
5
const glob = require("glob");

const files = glob.sync("path/to/files/*.txt");

console.log(files); // prints an array of all .txt files in path/to/files directory

10
11
12
13
14
15
16
17
18
19
    new TerserPlugin({ cache: true, parallel: true, sourceMap: false }),
    new OptimizeCSSAssetsPlugin({})
  ]
},
entry: {
  './js/app.js': glob.sync('./vendor/**/*.js').concat(['./js/app.js'])
},
output: {
  filename: 'app.js',
  path: path.resolve(__dirname, '../priv/static/js')
fork icon0
star icon15
watch icon0

34
35
36
37
38
39
40
41
42
var remotePath = 'https://' + process.env.EJ2_AZURE_CRED + '@' + appPath + '.scm.azurewebsites.net:443/' + appPath + '.git';
shelljs.exec('git init && git fetch ' + remotePath + ' master && git checkout master');
shelljs.exec('git pull ' + remotePath + ' master');

// get the removable files and remove it from cloned git repo
var rmFiles = glob.sync('./**/*', { ignore: ['./', './.git/**'] });
shelljs.rm('-rf', rmFiles);
// navigate to root folder
shelljs.cd('../');
fork icon27
star icon9
watch icon13

+ 15 other calls in file

14
15
16
17
18
19
20
21
22
23
24
25


const courseLangMap = {};
const lang_key = { en: 'English', hi: 'Hindi', ta: 'Tamil', te: 'Telugu' };


// Reads all properties files and create an object mapping of course to langauges in which content is available
const propFiles = glob.sync('**/PROPERTIES_FILES/**/*.json');
if (propFiles.length > 0) {
  _.map(propFiles, (fileName) => {
    // Extract the name of the course
    const name = fileName.split('/').pop().split('_')[0];
fork icon18
star icon15
watch icon4

474
475
476
477
478
479
480
481
482
483
if (_allMetadata === undefined) {
  let codelabs = [];
  let categories = {};
  let views = {};

  const viewFiles = glob.sync('app/views/*/view.json');
  for (let i = 0; i < viewFiles.length; i++) {
    const view = parseViewMetadata(viewFiles[i]);
    views[view.id] = view;
  }
fork icon2
star icon9
watch icon1

47
48
49
50
51
52
53
54
55
56
  transform: `@patternfly/react-table/dist/${env}`,
},
'@patternfly/react-core': {
  transform: (importName) => {
    let res;
    const files = glob.sync(
      path.resolve(
        __dirname,
        `./node_modules/@patternfly/react-core/dist/${env}/**/${
          mapper[importName] || importName
fork icon41
star icon8
watch icon12

16
17
18
19
20
21
22
23
24
25
26
27


const SANDBOX_SUFFIX = "-sandbox";


const config = {
  mode: isProd ? "production" : "development",
  entry: glob.sync("./src/widgets/**.tsx").reduce(function (obj, el) {
    obj[path.parse(el).name] = el;
    obj[path.parse(el).name + SANDBOX_SUFFIX] = el;
    return obj;
  }, {}),
fork icon3
star icon7
watch icon4

6292
6293
6294
6295
6296
6297
6298
6299
6300
6301

if (!exists(path)) {
  if (exists(path + '.js')) {
    path += '.js';
  } else {
    files = glob.sync(path);
    if (!files.length) {
      throw new Error("cannot resolve path (or pattern) '" + path + "'");
    }
    return files;
fork icon2
star icon6
watch icon4

257
258
259
260
261
262
263
264
265
  request.end()
}


// Require each JS file in the main-process dir
function loadMainProcesses () {
  const files = glob.sync(path.join(__dirname, 'process-main/**/*.js'))
  files.forEach((file) => { require(file) })
}
fork icon0
star icon5
watch icon2

72
73
74
75
76
77
78
79
80
81
    prune.push(e.substring(1));
    return false;
  }
  return true;
})).flatMap((e) => {
  return glob.sync(e);
}).filter((e) => {
  return prune.indexOf(e) < 0;
}).map((e) => {
  const ext = e.split('.').pop();
fork icon2
star icon2
watch icon15

383
384
385
386
387
388
389
390
391
392
393
*/
contextMenu();


// Require each JS file in the main-process dir
function loadDemos() {
  const files = glob.sync(path.join(__dirname, "main-process/**/*.js"));
  files.forEach((file) => {
    require(file);
  });
}
fork icon1
star icon2
watch icon6

+ 3 other calls in file

16
17
18
19
20
21
22
23
24
25
26
27


const SANDBOX_SUFFIX = '-sandbox';


const config = {
  mode: isProd ? 'production' : 'development',
  entry: glob.sync('./src/widgets/**.tsx').reduce(function (obj, el) {
    obj[path.parse(el).name] = el;
    obj[path.parse(el).name + SANDBOX_SUFFIX] = el;
    return obj;
  }, {}),
fork icon1
star icon3
watch icon1

+ 3 other calls in file

13
14
15
16
17
18
19
20
21
22
    new TerserPlugin({ cache: true, parallel: true, sourceMap: devMode }),
    new OptimizeCSSAssetsPlugin({})
  ]
},
entry: {
  'app': glob.sync('./vendor/**/*.js').concat(['./js/app.js'])
},
output: {
  filename: '[name].js',
  path: path.resolve(__dirname, '../priv/static/js'),
fork icon2
star icon2
watch icon0

4
5
6
7
8
9
10
11
12
13
14
15
16
const { apiResolver } = require('next/dist/server/api-utils/node');


const rootPath = path.resolve('.');
const nextPagesDirectory = fs.existsSync(`${rootPath}/pages`) ? `${rootPath}/pages` : `${rootPath}/src/pages`;


const handlers = glob.sync(`${nextPagesDirectory}/api/**/*.+(ts|js)`).map((handler) => handler.slice(nextPagesDirectory.length, -3));


const mapping = {};
handlers.forEach((handler) => {
  const key = handler.endsWith('/index') ? handler.slice(0, -6) : handler; // handle index routes
fork icon1
star icon3
watch icon1

395
396
397
398
399
400
401
402
403
404
if (this.area === this._owner.AREA.SRC) dirs.push(this._onwer.dir);
else dirs = [...dirs, ...this._onwer.dirs];

for (let i = 0; i < dirs.length; i++) {
    localPattern = path.join(dirs[i], pattern);
    arrPath = glob.sync(localPattern);
    arrPath.forEach(val => {
        subPath = path.relative(path.join(dirs[i], areaDir), val)
        alias = _this._makeAlias(subPath);
        content = fs.readFileSync(val,'utf-8');
fork icon0
star icon2
watch icon1

13
14
15
16
17
18
19
20
21
22
23


function getFiles(type) {
  var files = {};
  var recursive = (type === 'less');
  var globExpr = (recursive ? '/**/*' : '/*');
  glob.sync(type + globExpr)
    .filter(function (path) {
      return type === 'fonts' ? true : new RegExp('\\.' + type + '$').test(path);
    })
    .forEach(function (fullPath) {
fork icon0
star icon2
watch icon0

161
162
163
164
165
166
167
168
169
170
  // semtree options here...
});
const bonsaiText = {}; // { filename: content } hash
const rootFilename = 'root';
// build 'bonsaiText' hash
const files = glob.sync("./index/**/*.md", {});
files.forEach((file) => {
  const content = fs.readFileSync(file, { encoding: 'utf8' });
  const yamlData = matter(content);
  const basename = path.basename(file, '.md');
fork icon0
star icon1
watch icon0

+ 4 other calls in file