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

TypeScript fs.existsSync函数代码示例

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

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



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

示例1:

 diagnostics.forEach(uri => {
   if (!existsSync(uri.fsPath)) {
     toBeDeleted.push(uri)
   }
 })
开发者ID:bookman25,项目名称:vscode-jest,代码行数:5,代码来源:diagnostics.ts


示例2: main

async function main(): Promise<void> {
    tl.setResourcePath(path.join(__dirname, 'task.json'));
    let saveNpmrcPath: string;
    let npmrc = tl.getInput(constants.NpmAuthenticateTaskInput.WorkingFile);
    let workingDirectory = path.dirname(npmrc);
    if (!(npmrc.endsWith('.npmrc'))) {
        throw new Error(tl.loc('NpmrcNotNpmrc', npmrc));
    }
    else if (!tl.exist(npmrc)) {
        throw new Error(tl.loc('NpmrcDoesNotExist', npmrc));
    }
    else {
        console.log(tl.loc("AuthenticatingThisNpmrc", npmrc));
    }

    if (tl.getVariable("SAVE_NPMRC_PATH")) {
         saveNpmrcPath = tl.getVariable("SAVE_NPMRC_PATH");
    }
    else {
        let tempPath = tl.getVariable('Agent.BuildDirectory') || tl.getVariable('Agent.ReleaseDirectory') || process.cwd();
        tempPath = path.join(tempPath, 'npmAuthenticate');
        tl.mkdirP(tempPath);
        saveNpmrcPath = fs.mkdtempSync(tempPath + path.sep); 
        tl.setVariable("SAVE_NPMRC_PATH", saveNpmrcPath, false);
        tl.setVariable("NPM_AUTHENTICATE_TEMP_DIRECTORY", tempPath, false);
    }
    let npmrcTable: Object;

    //The index file is a json object that keeps track of where .npmrc files are saved.
    //There is a key-value pairing of filepaths of original npmrc files to IDs.
    //This is important so multiple runs of the npm Authenticate task on the same .npmrc file actually reverts to the original after the build completes.
    let indexFile = path.join(saveNpmrcPath, 'index.json');

    if (fs.existsSync(indexFile)) { //If the file exists, add to it.
        npmrcTable = JSON.parse(fs.readFileSync(indexFile, 'utf8'));
        
    }
    else { //If the file doesn't exist, create it. 
        npmrcTable = new Object();
        npmrcTable['index'] = 0;
    }

    if (npmrcTable[npmrc] === undefined) {
        npmrcTable[npmrc] = npmrcTable['index'];
        npmrcTable['index']++;
        fs.writeFileSync(indexFile, JSON.stringify(npmrcTable));
        util.saveFileWithName(npmrc, npmrcTable[npmrc], saveNpmrcPath);
    }

    let endpointRegistries: npmregistry.INpmRegistry[] = [];
    let endpointIds = tl.getDelimitedInput(constants.NpmAuthenticateTaskInput.CustomEndpoint, ',');
    if (endpointIds && endpointIds.length > 0) {
        await Promise.all(endpointIds.map(async e => {
            endpointRegistries.push(await npmregistry.NpmRegistry.FromServiceEndpoint(e, true));
        }));
    }

    let packagingLocation: pkgLocationUtils.PackagingLocation;
    try {
        packagingLocation = await pkgLocationUtils.getPackagingUris(pkgLocationUtils.ProtocolType.NuGet);
    } catch (error) {
        tl.debug('Unable to get packaging URIs, using default collection URI');
        tl.debug(JSON.stringify(error));
        const collectionUrl = tl.getVariable('System.TeamFoundationCollectionUri');
        packagingLocation = {
            PackagingUris: [collectionUrl],
            DefaultPackagingUri: collectionUrl
        };
    }
    let LocalNpmRegistries = await util.getLocalNpmRegistries(workingDirectory, packagingLocation.PackagingUris);
    
    let npmrcFile = fs.readFileSync(npmrc, 'utf8').split(os.EOL);
    for (let RegistryURLString of npmrcparser.GetRegistries(npmrc)) {
        let registryURL = URL.parse(RegistryURLString);
        let registry: npmregistry.NpmRegistry;
        if (endpointRegistries && endpointRegistries.length > 0) {
            for (let serviceEndpoint of endpointRegistries) {
                
                if (util.toNerfDart(serviceEndpoint.url) == util.toNerfDart(RegistryURLString)) {
                    let serviceURL = URL.parse(serviceEndpoint.url);              
                    console.log(tl.loc("AddingEndpointCredentials", registryURL.host));
                    registry = serviceEndpoint;
                    npmrcFile = clearFileOfReferences(npmrc, npmrcFile, serviceURL);
                    break;
                }
            }
        }
        if (!registry) {
            for (let localRegistry of LocalNpmRegistries) {
                if (util.toNerfDart(localRegistry.url) == util.toNerfDart(RegistryURLString)) {
                    let localURL = URL.parse(localRegistry.url);
                    console.log(tl.loc("AddingLocalCredentials"));
                    registry = localRegistry;
                    npmrcFile = clearFileOfReferences(npmrc, npmrcFile, localURL);
                    break;
                }
            }
        }
        if (registry) {
            tl.debug(tl.loc('AddingAuthRegistry', registry.url));
//.........这里部分代码省略.........
开发者ID:shubham90,项目名称:vsts-tasks,代码行数:101,代码来源:npmauth.ts


示例3: getNodeSystem

        function getNodeSystem(): System {
            var _fs = require("fs");
            var _path = require("path");
            var _os = require('os');

            var platform: string = _os.platform();
            // win32\win64 are case insensitive platforms, MacOS (darwin) by default is also case insensitive
            var useCaseSensitiveFileNames = platform !== "win32" && platform !== "win64" && platform !== "darwin";

            function readFile(fileName: string, encoding?: string): string {
                if (!_fs.existsSync(fileName)) {
                    return undefined;
                }
                var buffer = _fs.readFileSync(fileName);
                var len = buffer.length;
                if (len >= 2 && buffer[0] === 0xFE && buffer[1] === 0xFF) {
                    // Big endian UTF-16 byte order mark detected. Since big endian is not supported by node.js,
                    // flip all byte pairs and treat as little endian.
                    len &= ~1;
                    for (var i = 0; i < len; i += 2) {
                        var temp = buffer[i];
                        buffer[i] = buffer[i + 1];
                        buffer[i + 1] = temp;
                    }
                    return buffer.toString("utf16le", 2);
                }
                if (len >= 2 && buffer[0] === 0xFF && buffer[1] === 0xFE) {
                    // Little endian UTF-16 byte order mark detected
                    return buffer.toString("utf16le", 2);
                }
                if (len >= 3 && buffer[0] === 0xEF && buffer[1] === 0xBB && buffer[2] === 0xBF) {
                    // UTF-8 byte order mark detected
                    return buffer.toString("utf8", 3);
                }
                // Default is UTF-8 with no byte order mark
                return buffer.toString("utf8");
            }

            function writeFile(fileName: string, data: string, writeByteOrderMark?: boolean): void {
                // If a BOM is required, emit one
                if (writeByteOrderMark) {
                    data = '\uFEFF' + data;
                }

                _fs.writeFileSync(fileName, data, "utf8");
            }

            function getCanonicalPath(path: string): string {
                return useCaseSensitiveFileNames ? path.toLowerCase() : path;
            }

            function readDirectory(path: string, extension?: string, exclude?: string[]): string[] {
                var result: string[] = [];
                exclude = map(exclude, s => getCanonicalPath(combinePaths(path, s)));
                visitDirectory(path);
                return result;
                function visitDirectory(path: string) {
                    var files = _fs.readdirSync(path || ".").sort();
                    var directories: string[] = [];
                    for (let current of files) {
                        var name = combinePaths(path, current);
                        if (!contains(exclude, getCanonicalPath(name))) {
                            var stat = _fs.statSync(name);
                            if (stat.isFile()) {
                                if (!extension || fileExtensionIs(name, extension)) {
                                    result.push(name);
                                }
                            }
                            else if (stat.isDirectory()) {
                                directories.push(name);
                            }
                        }
                    }
                    for (let current of directories) {
                        visitDirectory(current);
                    }
                }
            }

            return {
                args: process.argv.slice(2),
                newLine: _os.EOL,
                useCaseSensitiveFileNames: useCaseSensitiveFileNames,
                write(s: string): void {
                    // 1 is a standard descriptor for stdout
                    _fs.writeSync(1, s);
                },
                readFile,
                writeFile,
                watchFile: (fileName, callback) => {
                    // watchFile polls a file every 250ms, picking up file notifications.
                    _fs.watchFile(fileName, { persistent: true, interval: 250 }, fileChanged);

                    return {
                        close() { _fs.unwatchFile(fileName, fileChanged); }
                    };

                    function fileChanged(curr: any, prev: any) {
                        if (+curr.mtime <= +prev.mtime) {
                            return;
//.........这里部分代码省略.........
开发者ID:Digitekstteksxbt,项目名称:TypeScript,代码行数:101,代码来源:sys.ts


示例4: it

 it('should delete the uploaded file', done => {
   expect(fs.existsSync(archivePath)).toBe(true);
   uploadPromise.
     then(() => expect(fs.existsSync(archivePath)).toBe(false)).
     then(done);
 });
开发者ID:JohnnyQQQQ,项目名称:angular,代码行数:6,代码来源:upload-server.e2e.ts


示例5:

 dirs = dirs.filter( (part) => {
     const packFile = path.join( root, part.replace(/\./g, '\\' ) ) + "\\package.cm";
     return fs.existsSync( packFile );
 } );
开发者ID:acauan,项目名称:vscode-cm,代码行数:4,代码来源:cmUtils.ts


示例6: run

    public run(onComplete: (status: number) => void) {
        if (this.options.version) {
            this.outputStream.write(Linter.VERSION + "\n");
            onComplete(0);
            return;
        }

        if (this.options.init) {
            if (fs.existsSync(CONFIG_FILENAME)) {
                console.error(`Cannot generate ${CONFIG_FILENAME}: file already exists`);
                onComplete(1);
                return;
            }

            const tslintJSON = JSON.stringify(DEFAULT_CONFIG, undefined, "    ");
            fs.writeFileSync(CONFIG_FILENAME, tslintJSON);
            onComplete(0);
            return;
        }

        if (this.options.test) {
            const results = runTests(this.options.test, this.options.rulesDirectory);
            const didAllTestsPass = consoleTestResultsHandler(results);
            onComplete(didAllTestsPass ? 0 : 1);
            return;
        }

        // when provided, it should point to an existing location
        if (this.options.config && !fs.existsSync(this.options.config)) {
            console.error("Invalid option for configuration: " + this.options.config);
            onComplete(1);
            return;
        }

        // if both files and tsconfig are present, use files
        let files = this.options.files === undefined ? [] : this.options.files;
        let program: ts.Program | undefined;

        if (this.options.project != null) {
            if (!fs.existsSync(this.options.project)) {
                console.error("Invalid option for project: " + this.options.project);
                onComplete(1);
                return;
            }
            program = Linter.createProgram(this.options.project, path.dirname(this.options.project));
            if (files.length === 0) {
                files = Linter.getFileNames(program);
            }
            if (this.options.typeCheck) {
                // if type checking, run the type checker
                const diagnostics = ts.getPreEmitDiagnostics(program);
                if (diagnostics.length > 0) {
                    const messages = diagnostics.map((diag) => {
                        // emit any error messages
                        let message = ts.DiagnosticCategory[diag.category];
                        if (diag.file) {
                            const {line, character} = diag.file.getLineAndCharacterOfPosition(diag.start);
                            message += ` at ${diag.file.fileName}:${line + 1}:${character + 1}:`;
                        }
                        message += " " + ts.flattenDiagnosticMessageText(diag.messageText, "\n");
                        return message;
                    });
                    throw new Error(messages.join("\n"));
                }
            } else {
                // if not type checking, we don't need to pass in a program object
                program = undefined;
            }
        }

        let ignorePatterns: string[] = [];
        if (this.options.exclude) {
            const excludeArguments: string[] = Array.isArray(this.options.exclude) ? this.options.exclude : [this.options.exclude];

            ignorePatterns = excludeArguments.map(Runner.trimSingleQuotes);
        }

        files = files
            // remove single quotes which break matching on Windows when glob is passed in single quotes
            .map(Runner.trimSingleQuotes)
            .map((file: string) => glob.sync(file, { ignore: ignorePatterns, nodir: true }))
            .reduce((a: string[], b: string[]) => a.concat(b), []);

        try {
            this.processFiles(onComplete, files, program);
        } catch (error) {
            if (error.name === FatalError.NAME) {
                console.error(error.message);
                onComplete(1);
            }
            // rethrow unhandled error
            throw error;
        }
    }
开发者ID:mark-buer,项目名称:tslint,代码行数:94,代码来源:runner.ts


示例7: then

then(() => expect(fs.existsSync(prDir)).toBe(false)).
开发者ID:JohnnyQQQQ,项目名称:angular,代码行数:1,代码来源:upload-server.e2e.ts


示例8: create_manifest_data

export default function create_manifest_data(cwd: string): ManifestData {
	// TODO remove in a future version
	if (!fs.existsSync(cwd)) {
		throw new Error(`As of Sapper 0.21, the routes/ directory should become src/routes/`);
	}

	function has_preload(file: string) {
		const source = fs.readFileSync(path.join(cwd, file), 'utf-8');

		if (/preload/.test(source)) {
			try {
				const { vars } = svelte.compile(source.replace(/<style\b[^>]*>[^]*?<\/style>/g, ''), { generate: false });
				return vars.some((variable: any) => variable.module && variable.export_name === 'preload');
			} catch (err) {}
		}

		return false;
	}

	function find_layout(file_name: string, component_name: string, dir: string = '') {
		const ext = component_extensions.find((ext) => fs.existsSync(path.join(cwd, dir, `${file_name}${ext}`)));
		const file = posixify(path.join(dir, `${file_name}${ext}`))

		return ext
			? {
				name: component_name,
				file: file,
				has_preload: has_preload(file)
			}
			: null;
	}

	const components: PageComponent[] = [];
	const pages: Page[] = [];
	const server_routes: ServerRoute[] = [];

	const default_layout: PageComponent = {
		default: true,
		type: 'layout',
		name: '_default_layout',
		file: null,
		has_preload: false
	};

	const default_error: PageComponent = {
		default: true,
		type: 'error',
		name: '_default_error',
		file: null,
		has_preload: false
	};

	function walk(
		dir: string,
		parent_segments: Part[][],
		parent_params: string[],
		stack: Array<{
			component: PageComponent,
			params: string[]
		}>
	) {
		const items = fs.readdirSync(dir)
			.map(basename => {
				const resolved = path.join(dir, basename);
				const file = path.relative(cwd, resolved);
				const is_dir = fs.statSync(resolved).isDirectory();

				const ext = path.extname(basename);

				if (basename[0] === '_') return null;
				if (basename[0] === '.' && basename !== '.well-known') return null;
				if (!is_dir && !/^\.[a-z]+$/i.test(ext)) return null; // filter out tmp files etc

				const segment = is_dir
					? basename
					: basename.slice(0, -ext.length);

				const parts = get_parts(segment);
				const is_index = is_dir ? false : basename.startsWith('index.');
				const is_page = component_extensions.indexOf(ext) !== -1;
				const route_suffix = basename.slice(basename.indexOf('.'), -ext.length);

				parts.forEach(part => {
					if (/\]\[/.test(part.content)) {
						throw new Error(`Invalid route ${file} — parameters must be separated`);
					}

					if (part.qualifier && /[\(\)\?\:]/.test(part.qualifier.slice(1, -1))) {
						throw new Error(`Invalid route ${file} — cannot use (, ), ? or : in route qualifiers`);
					}
				});

				return {
					basename,
					ext,
					parts,
					file: posixify(file),
					is_dir,
					is_index,
					is_page,
//.........这里部分代码省略.........
开发者ID:varholak-peter,项目名称:sapper,代码行数:101,代码来源:create_manifest_data.ts


示例9: isGitDirectory

export function isGitDirectory(directory: string): directory is GitDirectoryPath {
    return fs.existsSync(Path.join(directory, ".git") );
}
开发者ID:sunyton,项目名称:upterm,代码行数:3,代码来源:Git.ts


示例10: getExtraResource

async function getExtraResource() {
    const extraResourcesPath = __dirname + "/extra-resources";
    if (!existsSync(extraResourcesPath)) {
        mkdirSync(extraResourcesPath);
    }

    await download(
        DEFAULT_EXTENSIONS_CATALOG_VERSION_DOWNLOAD_URL,
        extraResourcesPath + "/catalog-version.json",
        "utf8"
    );

    const catalogJSON = await download(
        DEFAULT_EXTENSIONS_CATALOG_JSON_DOWNLOAD_URL,
        extraResourcesPath + "/catalog.json",
        "utf8"
    );
    const catalog = JSON.parse(catalogJSON);

    await download(
        DEFAULT_EXTENSIONS_CATALOG_ZIP_DOWNLOAD_URL,
        extraResourcesPath + "/catalog.zip",
        null
    );

    const db = new Database(__dirname + "/init_storage.db");
    const rows = db.prepare(`SELECT instrumentExtensionId FROM instrument`).all();

    const extensions: string[] = [];

    rows.push({
        instrumentExtensionId: "b278d8da-1c17-4baa-9837-1761b2481c2b"
    });

    for (const row of rows) {
        const instrumentExtensionId = row.instrumentExtensionId;

        let foundExtension: any;

        catalog.forEach((extension: any) => {
            if (extension.id === instrumentExtensionId) {
                if (
                    !foundExtension ||
                    compareVersions(extension.version, foundExtension.version) > 0
                ) {
                    foundExtension = extension;
                }
            }
        });

        if (!foundExtension) {
            console.warn(`Can't find extension ${instrumentExtensionId}`);
            return;
        }

        const extensionZipFileName = foundExtension.name + "-" + foundExtension.version + ".zip";
        const extensionZipFilePath = extraResourcesPath + "/" + extensionZipFileName;

        const extensionData = await download(foundExtension.download, extensionZipFilePath, null);

        if (sha256(extensionData) !== foundExtension.sha256) {
            console.log(sha256(extensionData));
            console.log(foundExtension.sha256);
            throw "Invalid hash for the extension zip file:" + extensionZipFileName;
        }

        extensions.push(extensionZipFilePath);
    }

    db.close();

    const extraResource = [
        __dirname + "/init_storage.db",
        extraResourcesPath + "/catalog-version.json",
        extraResourcesPath + "/catalog.json"
    ].concat(extensions);

    return extraResource;
}
开发者ID:eez-open,项目名称:studio,代码行数:79,代码来源:extra-resource.ts



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

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