本文整理汇总了TypeScript中fs.existsSync函数的典型用法代码示例。如果您正苦于以下问题:TypeScript existsSync函数的具体用法?TypeScript existsSync怎么用?TypeScript existsSync使用的例子?那么, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了existsSync函数的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的TypeScript代码示例。
示例1:
diagnostics.forEach(uri => {
if (!existsSync(uri.fsPath)) {
toBeDeleted.push(uri)
}
})
示例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));
//.........这里部分代码省略.........
示例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;
//.........这里部分代码省略.........
示例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);
});
示例5:
dirs = dirs.filter( (part) => {
const packFile = path.join( root, part.replace(/\./g, '\\' ) ) + "\\package.cm";
return fs.existsSync( packFile );
} );
示例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;
}
}
示例7: then
then(() => expect(fs.existsSync(prDir)).toBe(false)).
示例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,
//.........这里部分代码省略.........
示例9: isGitDirectory
export function isGitDirectory(directory: string): directory is GitDirectoryPath {
return fs.existsSync(Path.join(directory, ".git") );
}
示例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;
}