• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

TypeScript glob.sync函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了TypeScript中glob.sync函数的典型用法代码示例。如果您正苦于以下问题:TypeScript sync函数的具体用法?TypeScript sync怎么用?TypeScript sync使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了sync函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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


示例16: describe

    describe("replaceByRule", () => {
        const fixtureDir = "test/fixture/";
        const expectedDir = "test/expected/";

        glob.sync(`${fixtureDir}/*`).forEach(dir => {
            it(dir, () => {
                const prhYaml = path.join(dir, "prh.yml");
                const engine = fromYAMLFilePath(prhYaml);

                glob.sync(`${dir}/*`)
                    .filter(file => file !== prhYaml)
                    .forEach(file => {
                        const result = engine.replaceByRule(file);

                        const target = file.replace(fixtureDir, expectedDir);
                        if (fs.existsSync(target)) {
                            const expected = fs.readFileSync(target, { encoding: "utf8" });
                            assert(result === expected);

                        } else {
                            mkdirp.sync(path.dirname(target));
                            fs.writeFileSync(target, result);
                        }
                    });
            });
        });
    });
开发者ID:vvakame,项目名称:prh,代码行数:27,代码来源:engineSpec.ts


示例17: readDirAsMap

function readDirAsMap(dir: string): Map<string, string> {
  const files = new Map<string, string>();
  for (const filename of glob.sync('**', {cwd: dir, nodir: true})) {
    files.set(filename, fs.readFileSync(path.join(dir, filename)).toString());
  }
  return files;
}
开发者ID:Polymer,项目名称:tools,代码行数:7,代码来源:gen-ts_test.ts


示例18: minimatch

export const getModuleSourceDirectory = (state: ApplicationState) => {
  if (state.fileCache.length) {
    const pcFileCacheItem = state.fileCache.find((item) => (
      minimatch(state.options.projectConfig.sourceFilePattern, item.filePath)
    ));

    if (pcFileCacheItem) {
      return path.dirname(pcFileCacheItem.filePath);
    }
  }
  const sourceFiles = getModuleFilePaths(state);
  if (!sourceFiles.length) {

    if (minimatch(state.options.projectConfig.sourceFilePattern, DEFAULT_COMPONENT_SOURCE_DIRECTORY)) {
      return path.join(state.options.cwd,DEFAULT_COMPONENT_SOURCE_DIRECTORY);
    } else {

      // scan for ALL files and directories if source directory does not match
      const allFiles = glob.sync(state.options.projectConfig.sourceFilePattern.replace(/\.*\w+$/, ""));

      for (const file of allFiles) {
        if (fs.lstatSync(file).isDirectory()) {
          return file;
        }
      }
    }
  }

  return path.dirname(sourceFiles[0]);
}
开发者ID:cryptobuks,项目名称:tandem,代码行数:30,代码来源:index.ts


示例19: _getHashOf

function _getHashOf(pkg: PackageInfo): string {
  if (!(pkg.name in hashCache)) {
    hashCache[pkg.name] = null;
    const md5Stream = crypto.createHash('md5');

    // Update the stream with all files content.
    const files: string[] = glob.sync(path.join(pkg.root, '**'), { nodir: true });
    files.forEach(filePath => {
      md5Stream.write(`\0${filePath}\0`);
      md5Stream.write(fs.readFileSync(filePath));
    });
    // Update the stream with all versions of upstream dependencies.
    pkg.dependencies.forEach(depName => {
      md5Stream.write(`\0${depName}\0${_getHashOf(packages[depName])}\0`);
    });

    md5Stream.end();

    hashCache[pkg.name] = (md5Stream.read() as Buffer).toString('hex');
  }

  const value = hashCache[pkg.name];
  if (!value) {
    // Protect against circular dependency.
    throw new Error('Circular dependency detected between the following packages: '
      + Object.keys(hashCache).filter(key => hashCache[key] == null).join(', '));
  }

  return value;
}
开发者ID:fmalcher,项目名称:angular-cli,代码行数:30,代码来源:packages.ts


示例20: runCommand

    /* 编译模式 */
    runCommand(files: Array<string> = []): void {
      // 如果未指定文件类型则从配置文件中取
      if (!files.length) {
        let config = this.config;
        if (config.file || config.file.length) {
          for(let file of config.file) {
            file = file.replace(/\\/g, '/');
            files.push(path.resolve(this.basePath, file));
          }
        }
      }
      
      let fileList: Array<string> = [];

      for (let item of files) {
        let file = glob.sync(item);
        fileList = fileList.concat(file);
      }
      if (!fileList.length) {
        console.error('file not find');
        return;
      }
      fileList = this.checkIgnore(fileList);
      if (!fileList) {
        console.error('file ignore');
        return;
      }
      console.log('find files:\n'+fileList.join('\n'));
      fileList.map(this.compileCallback.bind(this));
    }
开发者ID:thinkjs,项目名称:autocommand-cli,代码行数:31,代码来源:watch.ts



注:本文中的glob.sync函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
TypeScript glob.Glob类代码示例发布时间:2022-05-25
下一篇:
TypeScript glob.hasMagic函数代码示例发布时间:2022-05-25
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap