path#extname TypeScript Examples

The following examples show how to use path#extname. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: utils.ts    From picgo-plugin-compress with MIT License 7 votes vote down vote up
export function getImageInfo(imageUrl: string, buffer: Buffer): ImageInfo {
  const { width, height } = imageSize(buffer)
  return {
    buffer,
    width: width as number,
    height: height as number,
    fileName: basename(imageUrl),
    extname: extname(imageUrl),
  }
}
Example #2
Source File: utils.ts    From yfm-docs with MIT License 7 votes vote down vote up
export function compareDirectories(expectedOutputPath: string, outputPath: string): CompareResult {
    const filesFromExpectedOutput = walkSync(expectedOutputPath, {
        directories: false,
        includeBasePath: false,
    });
    let compareResult: CompareResult = true;

    filesFromExpectedOutput.forEach((expectedFilePath) => {
        const fileExtension = extname(expectedFilePath);
        const expectedContent = getFileContent(resolve(expectedOutputPath, expectedFilePath));
        const outputContent = getFileContent(resolve(outputPath, expectedFilePath));

        const convertedExpectedContent = convertBackSlashToSlash(expectedContent);

        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        let preparedExpectedContent: any = convertedExpectedContent;
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        let preparedOutputContent: any = outputContent;

        if (fileExtension === '.yaml') {
            preparedExpectedContent = load(convertedExpectedContent);
            preparedOutputContent = load(outputContent);
        }

        if (!isEqual(preparedExpectedContent, preparedOutputContent)) {
            compareResult = {
                expectedContent: preparedExpectedContent,
                outputContent: preparedOutputContent,
            };
        }
    });

    return compareResult;
}
Example #3
Source File: find-files-with-extension-recursively.ts    From google-photos-exif with MIT License 6 votes vote down vote up
export async function findFilesWithExtensionRecursively(dirToSearch: string, extensionsToInclude: string[]): Promise<string[]> {
  const allFiles = await getAllFilesRecursively(dirToSearch);
  const dirIsEmpty = allFiles.length === 0;
  if (dirIsEmpty) {
    throw new Error('The search directory is empty, so there is no work to do. Check that your --inputDir contains all of the Google Takeout data, and that any zips have been extracted before running this tool');
  }

  const matchingFiles = allFiles.filter(filePath => {
    const extension = extname(filePath).toLowerCase();
    return extensionsToInclude.map(ext => ext.toLowerCase()).includes(extension.toLowerCase());
  });
  return matchingFiles;
}
Example #4
Source File: project.ts    From cli with Apache License 2.0 6 votes vote down vote up
private formatResourceFiles(dirPath = this.resourcePath) {
    const files = readdirSync(dirPath, {withFileTypes: true});
    files.forEach((file) => {
      const filePath = join(dirPath, file.name);
      if (file.isDirectory()) {
        this.formatResourceFiles(filePath);
        return;
      }
      if (file.isFile() && extname(filePath) === '.json') {
        const content = readJsonSync(filePath);
        writeJsonSync(filePath, content, Project.jsonFormat);
      }
    });
  }
Example #5
Source File: fileNode.ts    From vscode-ssh with MIT License 6 votes vote down vote up
async open() {
        if (this.file.attrs.size > 10485760) {
            vscode.window.showErrorMessage("File size except 10 MB, not support open!")
            return;
        }
        const extName = path.extname(this.file.filename).toLowerCase();
        if (extName == ".gz" || extName == ".exe" || extName == ".7z" || extName == ".jar" || extName == ".bin" || extName == ".tar") {
            vscode.window.showErrorMessage(`Not support open ${extName} file!`)
            return;
        }
        const { sftp } = await ClientManager.getSSH(this.sshConfig)
        const tempPath = await FileManager.record(`temp/${this.file.filename}`, null, FileModel.WRITE);
        sftp.fastGet(this.fullPath, tempPath, async (err) => {
            if (err) {
                vscode.window.showErrorMessage(err.message)
            } else {
                ConnectionProvider.tempRemoteMap.set(path.resolve(tempPath), { remote: this.fullPath, sshConfig: this.sshConfig })
                vscode.commands.executeCommand('vscode.open', vscode.Uri.file(tempPath))
            }
        })
    }
Example #6
Source File: patch.ts    From graphql-typed-document-node with MIT License 6 votes vote down vote up
export async function getAvailablePatches() {
  const baseDir = join(__dirname, './patches/');
  const files = readdirSync(baseDir).filter(d => extname(d) === '.patch');

  return {
    baseDir,
    availablePatches: files.map(fileName => {
      const cleanName = basename(fileName, extname(fileName));
      const parts = cleanName.split('+');
      const versionRange = parts.pop();
      const name = parts.join('/');

      return {
        fileName,
        details: {
          // This structure and fields are required internally in `patch-package` code.
          version: versionRange,
          name,
          pathSpecifier: name,
          humanReadablePathSpecifier: name,
          packageNames: [name],
        },
      };
    })
  };
}
Example #7
Source File: to-node.ts    From mordred with MIT License 6 votes vote down vote up
export async function fileToNode(filename: string, cwd: string, getType: typeof GetType): Promise<FileNode> {
  const absolutePath = join(cwd, filename)
  const content = await readFile(absolutePath, 'utf8')
  const { ctime, mtime } = await stat(absolutePath)
  return {
    id: getFileNodeId(filename),
    type: FILE_NODE_TYPE,
    mime: getType(extname(filename)),
    createdAt: ctime,
    updatedAt: mtime,    
    content,
    relativePath: filename,
    absolutePath,
    slug: filename.replace(/\.[a-zA-Z0-9]+$/, '')
  }
}
Example #8
Source File: traverse-module.ts    From erda-ui with GNU Affero General Public License v3.0 6 votes vote down vote up
function getModuleType(modulePath: string) {
  const moduleExt = extname(modulePath);
  if (JS_EXTS.some((ext) => ext === moduleExt)) {
    return MODULE_TYPES.JS;
  } else if (CSS_EXTS.some((ext) => ext === moduleExt)) {
    return MODULE_TYPES.CSS;
  } else if (JSON_EXTS.some((ext) => ext === moduleExt)) {
    return MODULE_TYPES.JSON;
  }
}
Example #9
Source File: utils.ts    From markdown-links with MIT License 6 votes vote down vote up
id = (path: string): string => {
  // Extracting file name without extension.
  return md5(path.substring(0, path.length - extname(path).length));
}
Example #10
Source File: parseRequestUrl.ts    From next-api-decorators with MIT License 6 votes vote down vote up
export function parseRequestUrl(req: NextApiRequest, directoryPath?: string, fileName?: string): string {
  // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
  const url = req.url!.split('?')[0];
  let path = url.split('/').slice(3).join('/');

  // The path for parametererized routes should be set to "/", in order for the methods to be matched.
  if (fileName?.startsWith('[')) {
    path = '/';
  }

  if (directoryPath && !fileName?.startsWith('[...')) {
    const pathRegExp = new RegExp(
      // "pages/api/articles/index.ts" is compiled into "pages/api/articles.js" which has to be appended to the directory path for parsing
      directoryPath.split('/.next/server/pages')[1].replace(/(\[\w+\])/, '(\\w+)') +
        (fileName && !fileName.startsWith('[...') && !fileName.startsWith('[[...')
          ? `/${basename(fileName, extname(fileName))}`
          : '')
    );
    /* istanbul ignore else */
    if (pathRegExp.test(url)) {
      path = url.replace(pathRegExp, '');
    }
  }

  if (!path.startsWith('/')) {
    path = `/${path}`;
  }

  return path;
}
Example #11
Source File: posts.ts    From blog with GNU General Public License v3.0 6 votes vote down vote up
getPostsMetdata = async (): Promise<PostMetadata[]> => {
    const dirContent: Dirent[] = await readDirAsync(postsPath, {
        withFileTypes: true,
        encoding: 'utf8'
    });

    return Promise.all(
        dirContent
            .filter(entry => entry.isFile() && extname(entry.name) === '.md')
            .map((entry) => {
                console.log(`Found file in posts: ${entry.name}`);
                return getPostMetadata(entry.name);
            })
    );
}
Example #12
Source File: swc.ts    From icepkg with MIT License 6 votes vote down vote up
resolveFile = (importee: string, isDir = false) => {
  const ext = extname(importee);
  if (ext === '') {
    for (let i = 0; i < RESOLVE_EXTENSIONS.length; ++i) {
      const path = isDir ? join(importee, `index${RESOLVE_EXTENSIONS[i]}`) : `${importee}${RESOLVE_EXTENSIONS[i]}`;
      const exist = fs.pathExistsSync(path);

      if (exist) return path;
    }
  }

  // File should suffix with `.js` in TypeScript project.
  if (ext === '.js') {
    const exist = fs.pathExistsSync(importee);
    // Leave other plugins to resolve it.
    if (exist) return null;

    const tsFilePath = importee.replace('.js', '.ts');
    const tsExist = fs.pathExistsSync(tsFilePath);

    if (tsExist) return tsFilePath;
  }
}
Example #13
Source File: create-rss.ts    From blog with GNU General Public License v3.0 6 votes vote down vote up
getPostMetadata = async (postFile: string): Promise<PostMetadata> => {
    const fileContent = await readFileAsync(join(postsPath, postFile), {
        encoding: 'utf8'
    });

    const result = matter(fileContent);
    const postId = basename(postFile, extname(postFile));

    return {
        title: result.data.title,
        abstract: result.data.abstract,
        created: parseISO(result.data.created),
        id: postId
    };
}
Example #14
Source File: function.ts    From aws-cdk-webpack-lambda-function with MIT License 6 votes vote down vote up
function preProcess(props: WebpackFunctionProps) {
  if (props.runtime && props.runtime.family !== RuntimeFamily.NODEJS) {
    throw new Error("Only `NODEJS` runtimes are supported.");
  }
  if (!/\.(js|ts)$/.test(props.entry)) {
    throw new Error("Only JavaScript or TypeScript entry files are supported.");
  }
  if (!existsSync(props.entry)) {
    throw new Error(`Cannot find entry file at ${props.entry}`);
  }
  if (!existsSync(props.config)) {
    throw new Error(`Cannot find webpack config file at ${props.config}`);
  }
  const handler = props.handler || "handler";
  const runtime = props.runtime || Runtime.NODEJS_14_X;
  const buildDir = props.buildDir || join(dirname(props.entry), ".build");
  const ensureUniqueBuildPath =
    typeof props.ensureUniqueBuildPath === "boolean"
      ? props.ensureUniqueBuildPath
      : true;
  const handlerDir = ensureUniqueBuildPath
    ? createUniquePath(buildDir, props.entry)
    : buildDir;
  const outputBasename = basename(props.entry, extname(props.entry));

  // Build with webpack
  const builder = new Builder({
    entry: resolve(props.entry),
    output: resolve(join(handlerDir, outputBasename + ".js")),
    config: resolve(props.config),
  });
  builder.build();
  return { runtime, handlerDir, outputBasename, handler };
}
Example #15
Source File: index.ts    From nestjs-proto-gen-ts with MIT License 6 votes vote down vote up
private output(file: string, pkg: string, tmpl: string): void {
        const root = new Root();

        this.resolveRootPath(root);

        root.loadSync(file, {
            keepCase: this.options.keepCase,
            alternateCommentMode: this.options.comments
        }).resolveAll();

        this.walkTree(root);

        const results = compile(tmpl)(root);
        const outputFile = this.options.output ? join(this.options.output, file.replace(/^.+?[/\\]/, '')) : file;
        const outputPath = join(dirname(outputFile), `${basename(file, extname(file))}.ts`);

        outputFileSync(outputPath, results, 'utf8');
    }
Example #16
Source File: Image.ts    From yumeko with GNU Affero General Public License v3.0 6 votes vote down vote up
public exec(msg: Message, content: string): string {
        const attachment = msg.attachments.first();
        if (attachment) {
            if (attachment.size > 0x7A1200) throw new CustomError("!PARSING", msg.ctx.lang("TYPE_IMAGE_SIZE_EXCEDED"));
            content = attachment.url;
        }
        let url: URL;
        try {
            url = new URL(content);
        } catch {
            const userType = (msg.client as YumekoClient).collector.runner.argsParser.getType("user");
            const user: User = userType(msg, content) as any;
            content = user.displayAvatarURL({ format: "png", size: 512, dynamic: true });
            url = new URL(content);
        }
        const ext = extname(url.pathname);
        if (!IMAGE_PATTERN.test(ext)) throw new CustomError("!PARSING",msg.ctx.lang("TYPE_IMAGE_UNSUPPORTED_EXT"));
        return content;
    }
Example #17
Source File: find-supported-media-files.ts    From google-photos-exif with MIT License 6 votes vote down vote up
export async function findSupportedMediaFiles(inputDir: string, outputDir: string): Promise<MediaFileInfo[]> {
  const supportedMediaFileExtensions = CONFIG.supportedMediaFileTypes.map(fileType => fileType.extension);
  const mediaFilePaths = await findFilesWithExtensionRecursively(inputDir, supportedMediaFileExtensions);

  const mediaFiles: MediaFileInfo[] = [];
  const allUsedOutputFilesLowerCased: string[] = [];

  for (const mediaFilePath of mediaFilePaths) {
    const mediaFileName = basename(mediaFilePath);
    const mediaFileExtension = extname(mediaFilePath);
    const supportsExif = doesFileSupportExif(mediaFilePath);

    const jsonFilePath = getCompanionJsonPathForMediaFile(mediaFilePath);
    const jsonFileName = jsonFilePath ? basename(jsonFilePath) : null;
    const jsonFileExists = jsonFilePath ? existsSync(jsonFilePath) : false;

    const outputFileName = generateUniqueOutputFileName(mediaFilePath, allUsedOutputFilesLowerCased);
    const outputFilePath = resolve(outputDir, outputFileName);

    mediaFiles.push({
      mediaFilePath,
      mediaFileName,
      mediaFileExtension,
      supportsExif,
      jsonFilePath,
      jsonFileName,
      jsonFileExists,
      outputFileName,
      outputFilePath,
    });
    allUsedOutputFilesLowerCased.push(outputFileName.toLowerCase());
  }

  return mediaFiles;
}
Example #18
Source File: esbuildDepPlugin.ts    From toy-vite with MIT License 6 votes vote down vote up
export function esbuildDepPlugin(deps: Record<string, string>): Plugin {
  return {
    name: 'dep-pre-bundle',
    setup(build) {
      build.onResolve(
        { filter: /^[\w@][^:]/ },
        async ({ path: id, importer, kind, resolveDir }) => {
          const isEntry = !importer;
          if (id in deps) {
            return isEntry
              ? { path: id, namespace: 'dep' }
              : { path: deps[id] };
          } else {
            return {};
          }
        },
      );

      // @ts-ignore
      build.onLoad({ filter: /.*/, namespace: 'dep' }, ({ path: id }) => {
        let contents: string = '';
        contents += `import d from "${deps[id]}";export default d;\n`;
        contents += `export * from "${deps[id]}";\n`;

        let loader = extname(deps[id]).slice(1);
        if (loader === 'mjs') {
          loader = 'js';
        }

        return {
          loader,
          contents,
          resolveDir: appRoot,
        };
      });
    },
  };
}
Example #19
Source File: color-picker.tsx    From uivonim with GNU Affero General Public License v3.0 6 votes vote down vote up
possiblyUpdateColorScheme = debounce(() => {
  if (!liveMode) return
  if (!window.api.nvimState().file.endsWith('.vim')) return

  const colorschemeBeingEdited = basename(
    window.api.nvimState().file,
    extname(window.api.nvimState().file)
  )
  const currentActiveColorscheme = window.api.nvimState().colorscheme

  if (currentActiveColorscheme !== colorschemeBeingEdited) return

  const cmd = (cmd: string) => window.api.invoke(Invokables.nvimCmd, cmd)
  cmd(`write`)
  cmd(`colorscheme ${currentActiveColorscheme}`)
  dispatch.pub('colorscheme.modified')
}, 300)
Example #20
Source File: system-font-manager.ts    From open-design-sdk with Apache License 2.0 6 votes vote down vote up
async _getMatchingFont(
    font: string,
    fontFamilies: SystemFontFamilies | null,
    params: {
      cancelToken: CancelToken
    }
  ): Promise<{ fontFilename: string; fontPostscriptName: string } | null> {
    const ext = extname(font)
    if (ext === '.ttf' || ext === '.otf') {
      try {
        const fontFilename = this._resolvePath(font)
        const fontInfo = await getFontInfo(fontFilename)
        params.cancelToken.throwIfCancelled()

        if (fontInfo) {
          return { fontFilename, fontPostscriptName: fontInfo.postscript }
        }
      } catch (err) {
        this._console.warn(
          'Font file path not resolved as a font file',
          font,
          err
        )
      }
    }
    if (ext === '.ttc') {
      console.error(
        'TrueTypeCollection (.ttc) font files cannot be used directly',
        font
      )
    }

    const fontFilename = await this._getFontPathByPostscriptName(
      font,
      fontFamilies,
      params
    )
    return fontFilename ? { fontFilename, fontPostscriptName: font } : null
  }
Example #21
Source File: files.ts    From the-fake-backend with ISC License 6 votes vote down vote up
/**
 * Read the fixture file.
 *
 * @param path The fixture path
 * @return The fixture content
 */
export function readFixtureFileSync(path: string): any {
  if (extname(path) === '.json') {
    return readJSONFileSync(path);
  }

  return readFileSync(path);
}
Example #22
Source File: DLabel.ts    From discord-qt with GNU General Public License v3.0 6 votes vote down vote up
private handleLinkHovered(link: string) {
    if (!link || link === '#') {
      this.setProperty('toolTip', '');

      return;
    }

    const uri = new URL(link);
    const name = uri.searchParams.get('emoji_name');

    // Hover over an emoji
    if (name) {
      const id = basename(uri.pathname, extname(uri.pathname));
      const emoji = app.client.emojis.resolve(id);
      const serverName = emoji?.guild.name;

      this.setProperty(
        'toolTip',
        `<html><b>:${name}:</b><br />
        ${
          serverName
            ? `${__('EMOJI_POPOUT_JOINED_GUILD_EMOJI_DESCRIPTION')} <b>${serverName}</b>`
            : __('EMOJI_POPOUT_PREMIUM_UNJOINED_PRIVATE_GUILD_DESCRIPTION')
        }
          </html>`
      );
    }
  }
Example #23
Source File: javascript.jest.transformer.ts    From askql with MIT License 6 votes vote down vote up
export function process(src: string, path: string) {
  if (path.endsWith('.pegjs')) {
    return peg.generate(src, {
      format: 'commonjs',
      output: 'source',
    });
  }

  if (path.endsWith('.ts') || path.endsWith('.tsx')) {
    // FIXME this does not fail on type errors!
    return ts.transpile(
      src,
      tsConfig.compilerOptions as Omit<ts.CompilerOptions, 'jsx'>,
      path,
      []
    );
  }

  if (path.endsWith('.js')) {
    return src;
  }

  if (path.endsWith('.ask')) {
    // TODO(mh): assert compiles
    return `module.exports = function () {
  return new Promise(askvm.bind(null, ${JSON.stringify(src)}, arguments));
};`;
  }

  throw new Error(`Invalid file extensions: ${extname(path)}`);
}
Example #24
Source File: FileExtractor.ts    From Bridge with GNU General Public License v3.0 6 votes vote down vote up
/**
   * Extract the chart from `this.sourceFolder`. (assumes there is exactly one archive file in that folder)
   */
  beginExtract() {
    setTimeout(this.cancelable(() => {
      readdir(this.sourceFolder, (err, files) => {
        if (err) {
          this.callbacks.error(extractErrors.readError(err), () => this.beginExtract())
        } else if (files.length == 0) {
          this.callbacks.error(extractErrors.emptyError(), () => this.beginExtract())
        } else {
          this.callbacks.start(files[0])
          this.extract(join(this.sourceFolder, files[0]), extname(files[0]) == '.rar')
        }
      })
    }), 100) // Wait for filesystem to process downloaded file
  }
Example #25
Source File: utils.ts    From picgo-plugin-compress with MIT License 6 votes vote down vote up
export function getUrlInfo(imageUrl: string) {
  return {
    fileName: basename(imageUrl),
    extname: extname(imageUrl),
  }
}
Example #26
Source File: Akairo.ts    From Mandroc with GNU General Public License v3.0 6 votes vote down vote up
AkairoHandler.prototype.load = function (
  thing: string | typeof AkairoModule,
  isReload: boolean
): AkairoModule {
  let Module: Class<AkairoModule>;
  if (typeof thing === "function") {
    Module = thing;
  } else {
    if (!this.extensions.has(extname(thing))) {
      return {} as AkairoModule;
    }

    const exported = this.findExport(require(thing));
    delete require.cache[require.resolve(thing)];

    if (!exported) {
      return {} as AkairoModule;
    }

    Module = exported;
  }

  if (!Module || !(Module.prototype instanceof this.classToHandle)) {
    return {} as AkairoModule;
  }

  const module: AkairoModule = new Module();
  if (this.modules.has(module.id)) {
    // @ts-expect-error
    throw new AkairoError("ALREADY_LOADED", this.classToHandle.name, module.id);
  }

  this.register(module, typeof thing === "function" ? undefined : thing);
  this.emit("load", module, isReload);

  return module;
};
Example #27
Source File: TestProject.ts    From yarn-plugins with MIT License 6 votes vote down vote up
public static async setup(): Promise<TestProject> {
    const dir = await tmp.dir();
    const pluginBundles = await globby('packages/*/bundles/**/*.js', {
      cwd: PROJECT_DIR,
    });
    const plugins = pluginBundles.map((src) => ({
      src,
      name: '@yarnpkg/' + basename(src, extname(src)),
      dest: posix.join('.yarn', 'plugins', ...src.split(sep).slice(3)),
    }));

    for (const path of plugins) {
      await copy(join(PROJECT_DIR, path.src), join(dir.path, path.dest));
    }

    const yarnConfig = safeLoad(
      await readFile(join(PROJECT_DIR, '.yarnrc.yml'), 'utf8'),
    ) as Record<string, unknown>;

    // Create .yarnrc.yml
    await outputFile(
      join(dir.path, '.yarnrc.yml'),
      safeDump({
        yarnPath: join(PROJECT_DIR, yarnConfig.yarnPath as string),
        plugins: plugins.map((plugin) => ({
          path: plugin.dest,
          spec: plugin.name,
        })),
      }),
    );

    // Create package.json
    await outputJSON(join(dir.path, 'package.json'), {
      private: true,
      workspaces: ['packages/*'],
    });

    return new TestProject(dir);
  }
Example #28
Source File: event-store.publisher.ts    From nestjs-geteventstore with MIT License 6 votes vote down vote up
protected getStreamName(
    correlationId: EventBase['metadata']['correlation_id'],
  ): string {
    const defaultName = process.argv?.[1]
      ? basename(process.argv?.[1], extname(process.argv?.[1]))
      : `${hostname()}_${process.argv?.[0] || 'unknown'}`;

    return `${this.config.serviceName || defaultName}-${correlationId}`;
  }
Example #29
Source File: format.ts    From Obsidian_to_Anki with GNU General Public License v3.0 6 votes vote down vote up
getAndFormatMedias(note_text: string): string {
		if (!(this.file_cache.hasOwnProperty("embeds"))) {
			return note_text
		}
		for (let embed of this.file_cache.embeds) {
			if (note_text.includes(embed.original)) {
				this.detectedMedia.add(embed.link)
				if (AUDIO_EXTS.includes(extname(embed.link))) {
					note_text = note_text.replace(new RegExp(c.escapeRegex(embed.original), "g"), "[sound:" + basename(embed.link) + "]")
				} else if (IMAGE_EXTS.includes(extname(embed.link))) {
					note_text = note_text.replace(
						new RegExp(c.escapeRegex(embed.original), "g"),
						'<img src="' + basename(embed.link) + '" alt="' + embed.displayText + '">'
					)
				} else {
					console.warn("Unsupported extension: ", extname(embed.link))
				}
			}
		}
		return note_text
	}