當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。