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

TypeScript path.basename函数代码示例

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

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



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

示例1:

 return files.map((filename) => path.basename(filename, '.json'));
开发者ID:nusmodifications,项目名称:nusmods,代码行数:1,代码来源:io.ts


示例2: extractVersion

function extractVersion(file): string {
    var result;
    result = path.basename(file);
    result = result.slice(0, result.indexOf('.transformation.js'))
    return result;
}
开发者ID:gintsgints,项目名称:typescriptdb,代码行数:6,代码来源:index.ts


示例3: handler


//.........这里部分代码省略.........
      console.log(`Directory ${chalk.cyan(projectPath)} must be empty.`)
      return
    }
  } else {
    fs.mkdirSync(projectPath)
  }

  // allow short handle boilerplate (e.g. `node-basic`)
  if (boilerplate && !boilerplate.startsWith('http')) {
    const matchedBoilerplate = defaultBoilerplates.find(
      b => b.name === boilerplate,
    )
    if (matchedBoilerplate) {
      boilerplate = matchedBoilerplate.repo
    } else {
      // allow shorthand GitHub URLs (e.g. `graphcool/graphcool-server-example`)
      boilerplate = getGitHubUrl(boilerplate)
    }
  }

  // interactive selection
  if (!boilerplate) {
    const maxNameLength = defaultBoilerplates
      .map(bp => bp.name.length)
      .reduce((max, x) => Math.max(max, x), 0)
    const choices = defaultBoilerplates.map(
      bp => `${padEnd(bp.name, maxNameLength + 2)} ${bp.description}`,
    )
    const { choice } = await context.prompt({
      type: 'list',
      name: 'choice',
      message: `Choose GraphQL boilerplate project:`,
      choices,
    })

    boilerplate = defaultBoilerplates[choices.indexOf(choice)].repo
  }

  // download repo contents
  const zipInfo = getZipInfo(boilerplate!)
  const downloadUrl = zipInfo.url
  const tmpFile = tmp.fileSync()

  console.log(`[graphql create] Downloading boilerplate from ${downloadUrl}...`)

  await new Promise(resolve => {
    request(downloadUrl)
      .pipe(fs.createWriteStream(tmpFile.name))
      .on('close', resolve)
  })

  const zip = new Zip(tmpFile.name)
  zip.extractEntryTo(zipInfo.path, projectPath, false)
  tmpFile.removeCallback()

  // run npm/yarn install
  if (!noInstall) {
    const subDirs = fs
      .readdirSync(projectPath)
      .map(f => path.join(projectPath, f))
      .filter(f => fs.statSync(f).isDirectory())
    const installPaths = [projectPath, ...subDirs]
      .map(dir => path.join(dir, 'package.json'))
      .filter(p => fs.existsSync(p))

    for (const packageJsonPath of installPaths) {
      process.chdir(path.dirname(packageJsonPath))
      console.log(
        `[graphql create] Installing node dependencies for ${packageJsonPath}...`,
      )
      if (commandExists.sync('yarn')) {
        await shell('yarn install')
      } else {
        await shell('npm install')
      }
    }
  }

  // change dir to projectPath for install steps
  process.chdir(projectPath)

  // run & delete setup script
  let installPath = path.join(projectPath, 'install.js')
  if (!fs.existsSync(installPath)) {
    installPath = path.join(projectPath, '.install')
  }

  if (fs.existsSync(installPath)) {
    console.log(`[graphql create] Running boilerplate install script... `)
    const installFunction = require(installPath)

    await installFunction({
      context,
      project: path.basename(projectPath),
      projectDir: directory,
    })

    rimraf.sync(installPath)
  }
}
开发者ID:koddsson,项目名称:graphql-cli,代码行数:101,代码来源:index.ts


示例4: done

		this.checkFilePatternAbsoluteMatch((exists, size) => {
			if (this.isCanceled) {
				return done(null, this.isLimitHit);
			}

			// Report result from file pattern if matching
			if (exists) {
				this.resultCount++;
				onResult({
					relativePath: this.filePattern,
					basename: path.basename(this.filePattern),
					size
				});

				// Optimization: a match on an absolute path is a good result and we do not
				// continue walking the entire root paths array for other matches because
				// it is very unlikely that another file would match on the full absolute path
				return done(null, this.isLimitHit);
			}

			// For each extra file
			if (extraFiles) {
				extraFiles.forEach(extraFilePath => {
					const basename = path.basename(extraFilePath);
					if (this.globalExcludePattern && this.globalExcludePattern(extraFilePath, basename)) {
						return; // excluded
					}

					// File: Check for match on file pattern and include pattern
					this.matchFile(onResult, { relativePath: extraFilePath /* no workspace relative path */, basename });
				});
			}

			let traverse = this.nodeJSTraversal;
			if (!this.maxFilesize) {
				if (this.useRipgrep) {
					this.traversal = Traversal.Ripgrep;
					traverse = this.cmdTraversal;
				} else if (platform.isMacintosh) {
					this.traversal = Traversal.MacFind;
					traverse = this.cmdTraversal;
					// Disable 'dir' for now (#11181, #11179, #11183, #11182).
				} /* else if (platform.isWindows) {
					this.traversal = Traversal.WindowsDir;
					traverse = this.windowsDirTraversal;
				} */ else if (platform.isLinux) {
					this.traversal = Traversal.LinuxFind;
					traverse = this.cmdTraversal;
				}
			}

			const isNodeTraversal = traverse === this.nodeJSTraversal;
			if (!isNodeTraversal) {
				this.cmdForkStartTime = Date.now();
			}

			// For each root folder
			flow.parallel<IFolderSearch, void>(folderQueries, (folderQuery: IFolderSearch, rootFolderDone: (err: Error, result: void) => void) => {
				this.call(traverse, this, folderQuery, onResult, onMessage, (err?: Error) => {
					if (err) {
						const errorMessage = toErrorMessage(err);
						console.error(errorMessage);
						this.errors.push(errorMessage);
						rootFolderDone(err, undefined);
					} else {
						rootFolderDone(undefined, undefined);
					}
				});
			}, (errors, result) => {
				const err = errors ? errors.filter(e => !!e)[0] : null;
				done(err, this.isLimitHit);
			});
		});
开发者ID:costincaraivan,项目名称:vscode,代码行数:73,代码来源:fileSearch.ts


示例5: getJsPath

function getJsPath(tsPath: string): string {
    return path.join(path.dirname(tsPath), path.basename(tsPath, ".ts")) + ".js";
}
开发者ID:CedarLogic,项目名称:NativeScript,代码行数:3,代码来源:tsc-dev.ts


示例6:

    path.isAbsolute('bar\\baz')   // false
    path.isAbsolute('.')         // false

    path.relative('C:\\orandea\\test\\aaa', 'C:\\orandea\\impl\\bbb')
    // returns
    //    '..\\..\\impl\\bbb'

    path.relative('/data/orandea/test/aaa', '/data/orandea/impl/bbb')
    // returns
    //    '../../impl/bbb'

    path.dirname('/foo/bar/baz/asdf/quux')
    // returns
    //    '/foo/bar/baz/asdf'

    path.basename('/foo/bar/baz/asdf/quux.html')
    // returns
    //    'quux.html'

    path.basename('/foo/bar/baz/asdf/quux.html', '.html')
    // returns
    //    'quux'

    path.extname('index.html')
    // returns
    //    '.html'

    path.extname('index.coffee.md')
    // returns
    //    '.md'
开发者ID:RomkeVdMeulen,项目名称:DefinitelyTyped,代码行数:30,代码来源:node-tests.ts


示例7: execute

    async execute(editor?: TextEditor, uri?: Uri, args: ShowQuickFileHistoryCommandArgs = {}) {
        uri = getCommandUri(uri, editor);
        if (uri == null) return commands.executeCommand(Commands.ShowQuickCurrentBranchHistory);

        const gitUri = await GitUri.fromUri(uri);

        if (args.showInView) {
            await Container.fileHistoryView.showHistoryForUri(gitUri);

            return undefined;
        }

        args = { ...args };

        const placeHolder = `${gitUri.getFormattedPath({
            suffix: args.reference ? ` (${args.reference.name})` : undefined
        })}${gitUri.sha ? ` ${Strings.pad(GlyphChars.Dot, 1, 1)} ${gitUri.shortSha}` : ''}`;

        const progressCancellation = FileHistoryQuickPick.showProgress(placeHolder);

        try {
            if (args.log === undefined) {
                args.log = await Container.git.getLogForFile(gitUri.repoPath, gitUri.fsPath, {
                    maxCount: args.maxCount,
                    range: args.range,
                    ref: (args.reference && args.reference.ref) || gitUri.sha
                });
                if (args.log === undefined) {
                    if (args.reference) {
                        return window.showWarningMessage(`The file could not be found in ${args.reference.name}`);
                    }
                    return Messages.showFileNotUnderSourceControlWarningMessage('Unable to show file history');
                }
            }

            if (progressCancellation !== undefined && progressCancellation.token.isCancellationRequested) {
                return undefined;
            }

            let previousPageCommand: CommandQuickPickItem | undefined = undefined;

            if (args.log.truncated) {
                let commandArgs: ShowQuickFileHistoryCommandArgs;
                commandArgs = { ...args, log: undefined };
                const npc = new CommandQuickPickItem(
                    {
                        label: '$(arrow-right) Show Next Commits',
                        description: `${Strings.pad(GlyphChars.Dash, 2, 3)} shows ${args.log.maxCount} newer commits`
                    },
                    Commands.ShowQuickFileHistory,
                    [gitUri, commandArgs]
                );

                const last = Iterables.last(args.log.commits.values());
                if (last != null) {
                    commandArgs = { ...args, log: undefined, nextPageCommand: npc };
                    previousPageCommand = new CommandQuickPickItem(
                        {
                            label: '$(arrow-left) Show Previous Commits',
                            description: `${Strings.pad(GlyphChars.Dash, 2, 3)} shows ${
                                args.log.maxCount
                            } older commits`
                        },
                        Commands.ShowQuickFileHistory,
                        [new GitUri(uri, last), commandArgs]
                    );
                }
            }

            const icon =
                args.reference instanceof GitTag
                    ? '$(tag) '
                    : args.reference instanceof GitBranch
                    ? '$(git-branch) '
                    : '';
            // Create a command to get back to where we are right now
            const currentCommand = new CommandQuickPickItem(
                {
                    label: `go back ${GlyphChars.ArrowBack}`,
                    description: `${Strings.pad(GlyphChars.Dash, 2, 3)} to history of ${
                        GlyphChars.Space
                    }$(file-text) ${paths.basename(gitUri.fsPath)}${
                        args.reference
                            ? ` from ${GlyphChars.Space}${icon}${args.reference.name}`
                            : gitUri.sha
                            ? ` from ${GlyphChars.Space}$(git-commit) ${gitUri.shortSha}`
                            : ''
                    }`
                },
                Commands.ShowQuickFileHistory,
                [uri, args]
            );

            const pick = await FileHistoryQuickPick.show(args.log, gitUri, placeHolder, {
                progressCancellation: progressCancellation,
                currentCommand: currentCommand,
                goBackCommand: args.goBackCommand,
                nextPageCommand: args.nextPageCommand,
                previousPageCommand: previousPageCommand,
                showAllCommand:
//.........这里部分代码省略.........
开发者ID:chrisleaman,项目名称:vscode-gitlens,代码行数:101,代码来源:showQuickFileHistory.ts


示例8: if

  export let run = () => {

    let files = [];
    if(program.file) {
      if(
        !fs.existsSync(program.file) ||
        !fs.existsSync(path.join(process.cwd(), program.file))
      ) {
        logger.fatal(`"${ program.file }" file wa not found`);
        process.exit(1);
      }
      else {
        files = [program.file];
      }
    }
    else if(program.tsconfig) {

      if(!fs.existsSync(program.tsconfig)) {
        logger.fatal('"tsconfig.json" file wa not found in the current directory');
        process.exit(1);
      }
      else {
        program.tsconfig = path.join(
          path.join(process.cwd(), path.dirname(program.tsconfig)),
          path.basename(program.tsconfig)
        );
        logger.info('using tsconfig', program.tsconfig);
        files = require(program.tsconfig).files;

        if(!files) {
          let exclude = [];
          exclude = require(program.tsconfig).exclude || [];

          var walk = (dir) => {
            let results = [];
            let list = fs.readdirSync(dir);
            list.forEach( (file) => {
              if (exclude.indexOf(file) < 0) {
                file = path.join(dir, file);
                let stat = fs.statSync(file);
                if (stat && stat.isDirectory()) {
                  results = results.concat(walk(file));
                }
                else if (path.extname(file) === '.ts') {
                  results.push(file);
                }
              }
            });
            return results;
          };

          files = walk('.');
        }
      }

    }
    else if (program.files) {
      logger.info('using files', program.files.length, 'file(s) found');
      files = program.files;
    }
    else {
      outputHelp()
    }

    let crawler = new Crawler.Dependencies(
      files
    );

    let deps = crawler.getDependencies();

    if(deps.length <= 0) {
      logger.info('No dependencies found');
      process.exit(0);
    }

    let engine = new Engine.Dot({
      output: program.output
    });
    engine
      .generateGraph(deps)
      .then( file => {

        if (program.open === true) {
          logger.info('openning file ', file);
          let open = require("opener");
          open(file);
        }

      })
      .catch( e => logger.error(e) )
      .finally( _ => logger.info('done'))

  }
开发者ID:mko,项目名称:angular2-dependencies-graph,代码行数:93,代码来源:application.ts


示例9: getName

export function getName(path: string, includeExt = true) {
	return basename(path, includeExt ? undefined : extname(path))
}
开发者ID:tpack,项目名称:utilskit,代码行数:3,代码来源:path.ts


示例10: historyFileName

        return [
            "-",
            "noglob",
            "nocorrect",
            "exec",
            "command",
        ];
    }

    get historyFileName(): string {
        return ".zsh_history";
    }
}

const supportedShells: Dictionary<Shell> = {
    bash: new Bash(),
    zsh: new ZSH() ,
};

const shell = () => {
    const shellName = basename(process.env.SHELL);
    if (shellName in supportedShells) {
        return process.env.SHELL;
    } else {
        console.error(`${shellName} is not supported; defaulting to /bin/bash`);
        return "/bin/bash";
    }
};

export const loginShell: Shell = supportedShells[basename(shell())];
开发者ID:LeiZeng,项目名称:black-screen,代码行数:30,代码来源:Shell.ts



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
TypeScript path.dirname函数代码示例发布时间:2022-05-25
下一篇:
TypeScript password-hash.verify函数代码示例发布时间: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