当前位置: 首页>>代码示例>>TypeScript>>正文


TypeScript fs-extra.existsSync函数代码示例

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


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

示例1: exportImage

export async function exportImage(kha: string, from: string, to: string, options: any, format: string, prealpha: boolean, poweroftwo: boolean = false): Promise<string> {
	if (format === undefined) {
		if (from.toString().endsWith('.png')) format = 'png';
		else if (from.toString().endsWith('.hdr')) format = 'hdr'; 
		else format = 'jpg';
	}

	if (format === 'jpg' && (options.scale === undefined || options.scale === 1) && options.background === undefined) {
		to = to + '.jpg';
	}
	else if (format === 'pvr') {
		to = to + '.pvr';
	}
	else if (format === 'hdr') {
		to = to + '.hdr';
	}
	else {
		format = 'png';
		if (prealpha) to = to + '.kng';
		else to = to + '.png';
	}
	
	let temp = to + '.temp';
	
	let outputformat = format;
	if (format === 'png' && prealpha) {
		outputformat = 'kng';
	}

	if (fs.existsSync(to) && fs.statSync(to).mtime.getTime() > fs.statSync(from.toString()).mtime.getTime()) {
		let wh = await getWidthAndHeight(kha, from, to, options, format, prealpha);
		options.original_width = wh.w;
		options.original_height = wh.h;
		return outputformat;
	}

	fs.ensureDirSync(path.dirname(to));

	if (format === 'jpg' || format === 'hdr') {
		fs.copySync(from, temp, { clobber: true });
		fs.renameSync(temp, to);
		let wh = await getWidthAndHeight(kha, from, to, options, format, prealpha);
		options.original_width = wh.w;
		options.original_height = wh.h;
		return outputformat;
	}

	const exe = 'kraffiti' + sys();
	
	let params = ['from=' + from, 'to=' + temp, 'format=' + format];
	if (!poweroftwo) {
		params.push('filter=nearest');
	}
	if (prealpha) params.push('prealpha');
	if (options.scale !== undefined && options.scale !== 1) {
		params.push('scale=' + options.scale);	
	}
	if (options.background !== undefined) {
		params.push('transparent=' + ((options.background.red << 24) | (options.background.green << 16) | (options.background.blue << 8) | 0xff).toString(16));
	}
	if (poweroftwo) {
		params.push('poweroftwo');
	}
	
	await convertImage(from, temp, to, kha, exe, params, options);
	return outputformat;
}
开发者ID:hammeron-art,项目名称:khamake,代码行数:67,代码来源:ImageTool.ts

示例2: isKhaProject

function isKhaProject(directory: string, projectfile: string) {
	return fs.existsSync(path.join(directory, 'Kha')) || fs.existsSync(path.join(directory, projectfile));
}
开发者ID:npretto,项目名称:khamake,代码行数:3,代码来源:main.ts

示例3: ensurePackage

export async function ensurePackage(
  options: IEnsurePackageOptions
): Promise<string[]> {
  let { data, pkgPath } = options;
  let deps: { [key: string]: string } = data.dependencies || {};
  let devDeps: { [key: string]: string } = data.devDependencies || {};
  let seenDeps = options.depCache || {};
  let missing = options.missing || [];
  let unused = options.unused || [];
  let messages: string[] = [];
  let locals = options.locals || {};

  // Verify dependencies are consistent.
  let promises = Object.keys(deps).map(async name => {
    if (!(name in seenDeps)) {
      seenDeps[name] = await getDependency(name);
    }
    if (deps[name] !== seenDeps[name]) {
      messages.push(`Updated dependency: ${name}@${seenDeps[name]}`);
    }
    deps[name] = seenDeps[name];
  });

  await Promise.all(promises);

  // Verify devDependencies are consistent.
  promises = Object.keys(devDeps).map(async name => {
    if (!(name in seenDeps)) {
      seenDeps[name] = await getDependency(name);
    }
    if (devDeps[name] !== seenDeps[name]) {
      messages.push(`Updated devDependency: ${name}@${seenDeps[name]}`);
    }
    devDeps[name] = seenDeps[name];
  });

  await Promise.all(promises);

  // For TypeScript files, verify imports match dependencies.
  let filenames: string[] = [];
  filenames = glob.sync(path.join(pkgPath, 'src/*.ts*'));
  filenames = filenames.concat(glob.sync(path.join(pkgPath, 'src/**/*.ts*')));

  if (!fs.existsSync(path.join(pkgPath, 'tsconfig.json'))) {
    if (utils.writePackageData(path.join(pkgPath, 'package.json'), data)) {
      messages.push('Updated package.json');
    }
    return messages;
  }

  let imports: string[] = [];

  // Extract all of the imports from the TypeScript files.
  filenames.forEach(fileName => {
    let sourceFile = ts.createSourceFile(
      fileName,
      fs.readFileSync(fileName).toString(),
      (ts.ScriptTarget as any).ES6,
      /*setParentNodes */ true
    );
    imports = imports.concat(getImports(sourceFile));
  });
  let names: string[] = Array.from(new Set(imports)).sort();
  names = names.map(function(name) {
    let parts = name.split('/');
    if (name.indexOf('@') === 0) {
      return parts[0] + '/' + parts[1];
    }
    return parts[0];
  });

  // Look for imports with no dependencies.
  promises = names.map(async name => {
    if (missing.indexOf(name) !== -1) {
      return;
    }
    if (name === '.' || name === '..') {
      return;
    }
    if (!deps[name]) {
      if (!(name in seenDeps)) {
        seenDeps[name] = await getDependency(name);
      }
      deps[name] = seenDeps[name];
      messages.push(`Added dependency: ${name}@${seenDeps[name]}`);
    }
  });

  await Promise.all(promises);

  // Look for unused packages
  Object.keys(deps).forEach(name => {
    if (options.noUnused === false) {
      return;
    }
    if (unused.indexOf(name) !== -1) {
      return;
    }
    const isTest = data.name.indexOf('test') !== -1;
    if (isTest) {
//.........这里部分代码省略.........
开发者ID:alexmorley,项目名称:jupyterlab,代码行数:101,代码来源:ensure-package.ts

示例4: require

import * as _ from 'lodash/fp'
import * as fs from 'fs-extra'
import * as path from 'path'
import chalk from 'chalk'

import { IErrorLine } from './interface'

const PROJECT_PACKAGE_PATH = path.join(process.cwd(), 'package.json')
const PROJECT_FOLDER_FILES = fs.readdirSync('./')
const TEST_FRAMEWORKS = ['jest', 'mocha', 'ava', 'tape', 'jesmine', 'karma']
const LINTERS = ['eslint', 'jslint', 'tslint', 'jshint']
const README = ['readme', 'readme.md', 'readme.markdown']
const GITIGNORE = ['.gitignore']
const EDITORCONFIG = ['.editorconfig']

if (!fs.existsSync(PROJECT_PACKAGE_PATH)) {
  console.log(chalk.red(`找不到${PROJECT_PACKAGE_PATH},请确定当前目录是Taro项目根目录!`))
  process.exit(1)
}
const projectPackage = require(PROJECT_PACKAGE_PATH)
const devDependencies = _.keysIn(_.get('devDependencies', projectPackage))

const inDevDependencies = dependencies => (_.intersectionBy(_.toLower, devDependencies, dependencies)).length > 0
const hasRecommandTestFrameworks = inDevDependencies(TEST_FRAMEWORKS)
const hasRecommandLinters = inDevDependencies(LINTERS)

const inProjectFolder = filenames => (_.intersectionBy(_.toLower, PROJECT_FOLDER_FILES, filenames)).length > 0
const hasReadme = inProjectFolder(README)
const hasGitignore = inProjectFolder(GITIGNORE)
const hasEditorconfig = inProjectFolder(EDITORCONFIG)
开发者ID:YangShaoQun,项目名称:taro,代码行数:30,代码来源:recommandValidator.ts

示例5: ensureDirExists

 ensureDirExists(Path.dirname(dir), () => {
     if (!fs.existsSync(dir)) { fs.mkdirSync(dir); }
     if (typeof cont === "function") { cont(); }
 });
开发者ID:rfrerebe,项目名称:Fable,代码行数:4,代码来源:index.ts

示例6: pack

    pack(module_name: string, callback: Function) {
        var baseFolder = global.clientAppRoot + "\\modules\\" + module_name + "\\";
        var manifest_file = fs.readJsonSync(baseFolder + consts.MANIFEST_NAME, { throws: false });
        //merge the manifest into the modules.json file
        if (manifest_file === null)
            callback("invalid json, try using ascii file");


        var zip = new JSZip();
        var filesArr: Array<any> = [];
        for (var i = 0; i < manifest_file.files.length; i++) {
            if (fs.existsSync(baseFolder + manifest_file.files[i])) {
                var fileContent = fs.readFileSync(baseFolder + manifest_file.files[i]);
                zip.file(manifest_file.files[i], fileContent);


            }


        }

        if (manifest_file.routes !== undefined) {
            var routeBase: string = serverRoot + "/routes/";
            for (var i = 0; i < manifest_file.routes.length; i++) {
                if (fs.existsSync(routeBase + manifest_file.routes[i].path)) {
                    var fileContent = fs.readFileSync(routeBase + manifest_file.routes[i].path);
                    zip.folder("routes").file(manifest_file.routes[i].path, fileContent);
                }

                var tsfile = routeBase + manifest_file.routes[i].path.replace('.js', '.ts');
                if (fs.existsSync(tsfile)) {
                    var fileContent = fs.readFileSync(tsfile);
                    zip.folder("routes").file(manifest_file.routes[i].path.replace('.js', '.ts'), fileContent);
                }


            }
        }


        if (manifest_file.scripts !== undefined) {
            for (var i = 0; i < manifest_file.scripts.length; i++) {
                if (fs.existsSync(baseFolder + "/scripts/" + manifest_file.scripts[i])) {
                    var fileContent = fs.readFileSync(baseFolder + "/scripts/" + manifest_file.scripts[i]);
                    zip.folder("scripts").file(manifest_file.scripts[i], fileContent);
                }
            }
        }





        if (fs.existsSync(baseFolder + "about.html")) {
            var fileContent = fs.readFileSync(baseFolder + "about.html");
            zip.file("about.html", fileContent);
        }




        var manifestContent = fs.readFileSync(baseFolder + consts.MANIFEST_NAME);
        zip.file(consts.MANIFEST_NAME, manifestContent);


        var content = zip.generate({ type: "nodebuffer" });
        var packageFileName = appRoot + "/nodulus_modules/" + module_name + ".zip";
        var packageBackupFileName = appRoot + "/nodulus_modules/" + module_name + "/" + module_name + "." + this.timestamp() + ".zip";

        if (fs.existsSync(packageFileName)) {
            fs.ensureDirSync(appRoot + "/nodulus_modules/" + module_name);
            fs.renameSync(packageFileName, packageBackupFileName);
        }
    
    
        //var oldPackage  = fs.readFileSync(global.appRoot + "/nodulus_modules/" + module_name + ".zip");
    
        // see FileSaver.js
        fs.writeFile(packageFileName, content, function (err: any) {
            if (err) throw err;
            callback(null, manifest_file);
        });



    }
开发者ID:gitter-badger,项目名称:nodulus,代码行数:86,代码来源:modules.ts

示例7: getTasks

    getTasks(environmentTasksDirectory).map((taskDirectory) => {
        const taskFilePath = path.join(taskDirectory.directory, "task.json");
        const task = fs.readJsonSync(taskFilePath) as AzureDevOpsTasksSchema;

        task.id = env.TaskIds[taskDirectory.name];
        if (task.id) {
            task.friendlyName += env.DisplayNamesSuffix;

            task.version = {
                Major: version.major,
                Minor: version.minor,
                Patch: version.patch,
            };

            if (task.helpMarkDown) {
                task.helpMarkDown = task.helpMarkDown.replace("#{Version}#", version.getVersionString());
            }

            if (task.inputs) {
                task.inputs.forEach((input) => {
                    const mappedType = endpointMap[input.type];
                    if (mappedType) {
                        input.type = mappedType;
                    }
                });
            }

            fs.writeJsonSync(taskFilePath, task);

            const taskLocFilePath = path.join(taskDirectory.directory, "task.loc.json");
            if (fs.existsSync(taskLocFilePath)) {
                const taskLoc = fs.readJsonSync(taskLocFilePath);
                taskLoc.id = env.TaskIds[taskDirectory.name];
                taskLoc.friendlyName += env.DisplayNamesSuffix;

                taskLoc.version.Major = version.major;
                taskLoc.version.Minor = version.minor;
                taskLoc.version.Patch = version.patch;
                if (taskLoc.helpMarkDown) {
                    taskLoc.helpMarkDown = taskLoc.helpMarkDown.replace("#{Version}#", version.getVersionString());
                }

                fs.writeJsonSync(taskLocFilePath, taskLoc);
                const locfilesDirectory = path.join(taskDirectory.directory, "Strings/resources.resjson");
                if (fs.existsSync(locfilesDirectory)) {
                    const langs = fs.readdirSync(locfilesDirectory);
                    for (const element of langs) {
                        const resourceFile = path.join(locfilesDirectory, element, "resources.resjson");
                        if (fs.existsSync(resourceFile)) {
                            const resource = fs.readJsonSync(resourceFile);
                            resource["loc.helpMarkDown"] = resource["loc.helpMarkDown"]
                                .replace("#{Version}#", version.getVersionString());
                            fs.writeJsonSync(resourceFile, resource);
                        }
                    }
                }
            }

            const taskId = taskDirectory.name.replace(/([A-Z])/g, "-$1").toLowerCase().replace(/^[-]+/, "");
            extension.contributions.push({
                description: task.description,
                id: taskId + "-task",
                properties: {
                    name: "Tasks/" + taskDirectory.name,
                },
                targets: [
                    "ms.vss-distributed-task.tasks",
                ],
                type: "ms.vss-distributed-task.task",
            });
        } else {
            fs.removeSync(taskDirectory.directory);
        }
    });
开发者ID:geeklearningio,项目名称:gl-vsts-tasks-build-scripts,代码行数:74,代码来源:package.ts

示例8:

 ['lib', 'node_modules', 'static'].forEach(folder => {
   let folderPath = path.join('.', name, folder);
   if (fs.existsSync(folderPath)) {
     fs.remove(folderPath);
   }
 });
开发者ID:7125messi,项目名称:jupyterlab,代码行数:6,代码来源:create-theme.ts

示例9: dynamicPathParser

export function dynamicPathParser(options: DynamicPathOptions) {
  const projectRoot = options.project.root;
  const sourceDir = options.appConfig.root;
  const appRoot = path.join(sourceDir, 'app');
  const cwd = process.env.PWD;

  const rootPath = path.join(projectRoot, appRoot);
  let outputPath = path.join(rootPath, options.entityName);

  if (options.entityName.indexOf(path.sep) === 0) {
    outputPath = path.join(rootPath, options.entityName.substr(1));
  } else if (cwd.indexOf(rootPath) >= 0) {
    outputPath = path.join(cwd, options.entityName);
  }

  if (!fs.existsSync(outputPath)) {
    // Verify the path exists on disk.
    const parsedOutputPath = path.parse(outputPath);
    const parts = parsedOutputPath.dir.split(path.sep).slice(1);
    const newPath = parts.reduce((tempPath: string, part: string) => {
      // if (tempPath === '') {
      //   return part;
      // }

      const withoutPlus = path.join(tempPath, part);
      const withPlus = path.join(tempPath, '+' + part);
      if (fs.existsSync(withoutPlus)) {
        return withoutPlus;
      } else if (fs.existsSync(withPlus)) {
        return withPlus;
      }

      // Folder not found, create it, and return it
      const dasherizedPart = stringUtils.dasherize(part);
      const dasherizedDirName = path.join(tempPath, dasherizedPart);
      if (!options.dryRun) {
        fs.mkdirpSync(dasherizedDirName);
      }
      return dasherizedDirName;

    }, parsedOutputPath.root);
    outputPath = path.join(newPath, parsedOutputPath.name);
  }

  if (outputPath.indexOf(rootPath) < 0) {
    throw `Invalid path: "${options.entityName}" cannot be ` +
        `above the "${appRoot}" directory`;
  }

  const adjustedPath = outputPath.replace(projectRoot, '');

  const parsedPath = path.parse(adjustedPath);

  if (parsedPath.dir.indexOf(path.sep) === 0) {
    parsedPath.dir = parsedPath.dir.substr(1);
  }

  parsedPath.dir = parsedPath.dir === path.sep ? '' : parsedPath.dir;

  return { ...parsedPath, appRoot, sourceDir };
}
开发者ID:RoPP,项目名称:angular-cli,代码行数:61,代码来源:dynamic-path-parser.ts

示例10:

 [autoPep8FileToFormat, autoPep8FileToAutoFormat, yapfFileToFormat, yapfFileToAutoFormat].forEach(file => {
     if (fs.existsSync(file)) { fs.unlinkSync(file); }
     fs.copySync(originalUnformattedFile, file);
 });
开发者ID:SongJLG,项目名称:pythonVSCode,代码行数:4,代码来源:extension.format.test.ts


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