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


TypeScript path.basename函數代碼示例

本文整理匯總了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;未經允許,請勿轉載。