當前位置: 首頁>>代碼示例>>TypeScript>>正文


TypeScript glob.sync函數代碼示例

本文整理匯總了TypeScript中glob.sync函數的典型用法代碼示例。如果您正苦於以下問題:TypeScript sync函數的具體用法?TypeScript sync怎麽用?TypeScript sync使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。


在下文中一共展示了sync函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的TypeScript代碼示例。

示例1: loadPatterns

export default
function loadPatterns(): TestPattern[] {
  const yamlGlob = path.join(__dirname, "../../../src/test/patterns/**/*.yml");
  const yamlPaths: string[] = glob.sync(yamlGlob);
  return yamlPaths
    .map(path => yaml.safeLoad(fs.readFileSync(path, "utf8")))
    .reduce((x, y) => x.concat(y));
}
開發者ID:seanchas116,項目名稱:macaron,代碼行數:8,代碼來源:loadPattern.ts

示例2: getGrapherExportsByUrl

export async function getGrapherExportsByUrl(): Promise<{ get: (grapherUrl: string) => ChartExportMeta }> {
    // Index the files to see what we have available, using the most recent version
    // if multiple exports exist
    const files = glob.sync(`${BAKED_SITE_DIR}/exports/*.svg`)
    const exportsByKey = new Map()
    for (const filepath of files) {
        const filename = path.basename(filepath)
        const [key, version, dims] = filename.split("_")
        const versionNumber = parseInt(version.split('v')[1])
        const [width, height] = dims.split("x")

        const current = exportsByKey.get(key)
        if (!current || current.version < versionNumber) {
            exportsByKey.set(key, {
                key: key,
                svgUrl: `${BAKED_BASE_URL}/exports/${filename}`,
                version: versionNumber,
                width: parseInt(width),
                height: parseInt(height)
            })
        }
    }

    return {
        get(grapherUrl: string) {
            return exportsByKey.get(grapherUrlToFilekey(grapherUrl))
        }
    }
}
開發者ID:OurWorldInData,項目名稱:owid-grapher,代碼行數:29,代碼來源:grapherUtil.ts

示例3: findLazyModules

export function findLazyModules(projectRoot: any): {[key: string]: string} {
  const result: {[key: string]: string} = {};
  glob.sync(path.join(projectRoot, '/**/*.ts'))
    .forEach(tsPath => {
      findLoadChildren(tsPath).forEach(moduleName => {
        let fileName = moduleName.startsWith('.')
          ? path.resolve(path.dirname(tsPath), moduleName) + '.ts'
          : path.resolve(projectRoot, moduleName) + '.ts';

        if (fs.existsSync(fileName)) {
          // Put the moduleName as relative to the main.ts.
          result[moduleName] = fileName;
        } else {
          try {
            let res = resolve.sync(moduleName, { basedir: projectRoot });
            if (res) {
              result[moduleName] = res;
            }
          } catch (e) {
          }
        }
      });
    });
  return result;
}
開發者ID:devCrossNet,項目名稱:angular-cli,代碼行數:25,代碼來源:find-lazy-modules.ts

示例4: describe

describe('Error Test', () => {
  var errorFileNames = glob.sync('./test/fixtures/typings/errors/**/*.ts');

  errorFileNames.forEach((errorFileName) => {
    context(errorFileName.replace('./test/fixtures/typings/errors/', ''), () => {
      var plugin = typhen.loadPlugin('./test/fixtures/plugin/typhen-test', {
        author: 'shiwano'
      });

      before((done) => {
        rimraf('./.tmp/generated', done);
      });

      it('should raise error', (done) => {
        typhen.run({
          plugin: plugin,
          src: errorFileName,
          dest: '.tmp/generated'
        }).catch(e => {
          done();
        });
      });

      it('should not generate anything', (done) => {
        glob('./.tmp/generated/**/*.md', (err, fileNames) => {
          assert(fileNames.length === 0);
          done();
        });
      });
    });
  });
});
開發者ID:latotty,項目名稱:typhen,代碼行數:32,代碼來源:error_test.ts

示例5: describe

describe("react-icon-loader", async () => {
  const svgFiles = glob.sync("node_modules/material-design-icons/action/svg/design/*48px.svg");

  for (const file of svgFiles) {
    test(`cli ${file}`, async () => {
      await cli(file);
    });
  }

  test("compile", async () => {
    const tsFiles = glob.sync("node_modules/material-design-icons/action/svg/design/*.ts");
    expect(tsFiles).toHaveLength(svgFiles.length);
    const tsRes = await exec(`./node_modules/.bin/tsc ${tsFiles.join(" ")}`);
    expect(tsRes.stderr).toHaveLength(0);
  });

  test("exec", async () => {
    const jsFiles = glob.sync("node_modules/material-design-icons/action/svg/design/*.js");
    expect(jsFiles).toHaveLength(svgFiles.length);
    for (const file of jsFiles) {
      const nodeRes = await exec(`node ${file}`);
      expect(nodeRes.stderr).toHaveLength(0);
    }
  });
});
開發者ID:barbuza,項目名稱:react-icon-loader,代碼行數:25,代碼來源:cli.spec.ts

示例6: markdownFilesInDir

export function markdownFilesInDir(dirName: string): AbsoluteFilePath[] {
  const files = glob.sync(`${dirName}/**/*.md`)
  return files
    .filter(file => !file.includes('node_modules'))
    .sort()
    .map(file => new AbsoluteFilePath(file))
}
開發者ID:Originate,項目名稱:tutorial-runner,代碼行數:7,代碼來源:markdown-files-in-dir.ts

示例7:

const findCoverFile = (dirname: string): string => {
  const preferredFilenames = [
    'cover.jpg',
    'cover.jpeg',
    'folder.jpg',
    'folder.jpeg',
    'front.jpg',
    'front.jpeg'
  ];

  const filepaths = glob.sync('**/*.{jpeg,jpg}', { cwd: dirname });

  let found;

  for (const filepath of filepaths) {
    const base = path.basename(filepath).toLowerCase();
    if (preferredFilenames.indexOf(path.basename(base)) > -1) {
      found = filepath;
    }

    if (found) {
      continue;
    }

    found = filepath;
  }

  if (found) {
    const resolved = path.resolve(dirname, found);
    log.debug('Found cover art file: %s', resolved);
    return resolved;
  }

  return '';
};
開發者ID:mshick,項目名稱:arrivals-osx,代碼行數:35,代碼來源:convertAudio.ts

示例8: describe

describe('full repo', () => {
	if (!fs.existsSync(repoDir)) {
		return;
	}

	let files = glob.sync('types/*/index.d.ts', {
		cwd: repoDir
	});

	files.sort();

	files.forEach((file) => {
		let targetPath = path.join(repoDir, file);

		it(file, () => {
			let sourceData = fs.readFileSync(targetPath, {encoding: 'utf8'});
			let result = DH.parse(sourceData);
			if (!result.success) {
				if (DH.isPartial(sourceData)) {
					return;
				}
				console.log(DH.utils.linkPos(targetPath, result.line, result.column));
				console.log('\n' + result.details + '\n');
			}
			assert.isTrue(result.success, result.message);
		});
	});
});
開發者ID:DefinitelyTyped,項目名稱:definition-header,代碼行數:28,代碼來源:repo.test.ts

示例9:

        >((agg, thresholdGroup) => {
          const absoluteThresholdGroup = path.resolve(thresholdGroup);

          // The threshold group might be a path:

          if (file.indexOf(absoluteThresholdGroup) === 0) {
            groupTypeByThresholdGroup[thresholdGroup] =
              THRESHOLD_GROUP_TYPES.PATH;
            return agg.concat([[file, thresholdGroup]]);
          }

          // If the threshold group is not a path it might be a glob:

          // Note: glob.sync is slow. By memoizing the files matching each glob
          // (rather than recalculating it for each covered file) we save a tonne
          // of execution time.
          if (filesByGlob[absoluteThresholdGroup] === undefined) {
            filesByGlob[absoluteThresholdGroup] = glob
              .sync(absoluteThresholdGroup)
              .map(filePath => path.resolve(filePath));
          }

          if (filesByGlob[absoluteThresholdGroup].indexOf(file) > -1) {
            groupTypeByThresholdGroup[thresholdGroup] =
              THRESHOLD_GROUP_TYPES.GLOB;
            return agg.concat([[file, thresholdGroup]]);
          }

          return agg;
        }, []);
開發者ID:facebook,項目名稱:jest,代碼行數:30,代碼來源:coverage_reporter.ts

示例10: allMarkdownFiles

export function allMarkdownFiles(fileGlob: string): AbsoluteFilePath[] {
  return glob
    .sync(fileGlob)
    .filter(file => !file.includes('node_modules'))
    .sort()
    .map(file => new AbsoluteFilePath(file))
}
開發者ID:Originate,項目名稱:tutorial-runner,代碼行數:7,代碼來源:all-markdown-files.ts

示例11: _

 var foundFile = _(results).chain().map(file => {
     var g = glob.sync(file);
     if (g && g.length) {
         return g[0];
     }
     return false;
 }).find(z => !!z).value();
開發者ID:Alxandr,項目名稱:omnisharp-atom,代碼行數:7,代碼來源:project-finder.ts

示例12: parser

  /**
   * 解析節點樹
   *
   * @param {(Xcx.Entry | Xcx.Entry[])} entry
   * @returns {XcxNode[]}
   * @memberof Xcx
   */
  parser (entry: Xcx.Entry | Xcx.Entry[]): XcxNode[] {
    let xcxNodes: XcxNode[] = []

    if (_.isArray(entry)) {
      entry.forEach(item => {
        xcxNodes = [...xcxNodes, ...this.parser(item)]
      })
    } else {
      if (entry.isGlob) {
        // 搜索文件結果
        let requests = glob.sync(entry.request, {
          cwd: entry.parent || config.cwd
        })
        // 創建入口文件配置
        let list: Xcx.Entry[] = requests.map(request => {
          return {
            ..._.omit(entry, 'isGlob'),
            request
          }
        })
        // 遍曆
        xcxNodes = [...xcxNodes, ...this.parser(list)]
      } else {
        // 創建節點樹
        let xcxNode = XcxNode.create(entry)
        if (xcxNode) {
          xcxNodes.push(xcxNode)
        }
      }
    }
    return xcxNodes
  }
開發者ID:bbxyard,項目名稱:bbxyard,代碼行數:39,代碼來源:Xcx.ts

示例13: trueCasePathSync

export function trueCasePathSync(fsPath: string): string {
	// Normalize the path so as to resolve . and .. components.
	// !! As of Node v4.1.1, a path starting with ../ is NOT resolved relative
	// !! to the current dir, and glob.sync() below then fails.
	// !! When in doubt, resolve with fs.realPathSync() *beforehand*.
	let fsPathNormalized = path.normalize(fsPath);

	// OSX: HFS+ stores filenames in NFD (decomposed normal form) Unicode format,
	// so we must ensure that the input path is in that format first.
	if (process.platform === "darwin")
		fsPathNormalized = fsPathNormalized.normalize("NFD");

	// !! Windows: Curiously, the drive component mustn't be part of a glob,
	// !! otherwise glob.sync() will invariably match nothing.
	// !! Thus, we remove the drive component and instead pass it in as the 'cwd'
	// !! (working dir.) property below.
	const pathRoot = path.parse(fsPathNormalized).root;
	const noDrivePath = fsPathNormalized.slice(Math.max(pathRoot.length - 1, 0));

	// Perform case-insensitive globbing (on Windows, relative to the drive /
	// network share) and return the 1st match, if any.
	// Fortunately, glob() with nocase case-corrects the input even if it is
	// a *literal* path.
	return glob.sync(noDrivePath, { nocase: true, cwd: pathRoot })[0];
}
開發者ID:DanTup,項目名稱:Dart-Code,代碼行數:25,代碼來源:utils.ts

示例14: assert

      .then(() => {
        console.log(`>>> i18n extraction done, asserting read and wrote files`);

        const allFiles = glob.sync(path.join(basePath, '**/*'), {nodir: true});

        assert(wroteFiles.length == 1, `Expected a single message bundle file.`);

        assert(
            wroteFiles[0].endsWith('/ngtools_src/messages.xlf'),
            `Expected the bundle file to be "message.xlf".`);

        allFiles.forEach((fileName: string) => {
          // Skip tsconfig.
          if (fileName.match(/tsconfig-build.json$/)) {
            return;
          }

          // Assert that file was read.
          if (fileName.match(/\.css$/) || fileName.match(/\.html$/)) {
            assert(
                readResources.indexOf(fileName) != -1,
                `Expected resource "${fileName}" to be read.`);
          }
        });

        console.log(`done, no errors.`);
      })
開發者ID:diestrin,項目名稱:angular,代碼行數:27,代碼來源:test_ngtools_api.ts

示例15: copyDir

export async function copyDir(src: string, dest: string, filter: CopyFilter = defaultFilter) {
  if (!path.isAbsolute(dest)) {
    dest = path.resolve(process.PROJECT_LOCATION, dest)
  }

  ensureDirSync(dest)

  let files = glob.sync('**/*', { cwd: src, nodir: true, dot: true })

  if (filter) {
    files = files.filter(filter)
  }

  return Promise.mapSeries(files, f =>
    Promise.fromCallback(async cb => {
      const fileDest = path.join(dest, f)
      const fileDir = path.dirname(fileDest)

      if (fileDir.length) {
        ensureDirSync(fileDir)
      }

      const buffer = await Promise.fromCallback(cb => {
        fs.readFile(path.join(src, f), cb)
      })

      fs.writeFile(fileDest, buffer, cb)
    })
  )
}
開發者ID:alexsandrocruz,項目名稱:botpress,代碼行數:30,代碼來源:pkg-fs.ts


注:本文中的glob.sync函數示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。