fs#existsSync TypeScript Examples
The following examples show how to use
fs#existsSync.
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 atom-languageclient with MIT License | 7 votes |
/**
* Finds an exe file in the package assuming it is placed under `rootPath/platform-arch/exe`. If the exe file did not
* exist, the given name is returned. For example on Windows x64, if the `exeName` is `serve-d`, it returns the absolute
* path to `./bin/win32-x64/exeName.exe`, and if the file did not exist, `serve-d` is returned.
*
* @param exeName Name of the exe file
* @param rootPath The path of the folder of the exe file. Defaults to 'join("bin", `${process.platform}-${process.arch}`)'
* @param exeExtention The extention of the exe file. Defaults to `process.platform === "win32" ? ".exe" : ""`
*/
export function getExePath(exeName: string, rootPath = rootPathDefault, exeExtention = exeExtentionDefault): string {
const exePath = resolve(join(rootPath, `${exeName}${exeExtention}`))
if (existsSync(exePath)) {
return exePath
} else {
return exeName
}
}
Example #2
Source File: main.ts From node-mavlink with GNU Lesser General Public License v3.0 | 6 votes |
async function configure() {
return yargs(process.argv.slice(2))
.command('e2e', 'Execute end to end serialization/deserialization verification',
yargs => yargs.positional('input', {
description: 'Input file (- for stdin)',
default: '-'
}),
argv => {
if (argv.input !== '-' && !existsSync(argv.input)) {
console.error(`error: ${argv.input} not found`)
process.exit(1)
}
}
)
.help()
.alias('help', 'h')
.parse()
}
Example #3
Source File: breakpointHandler.ts From vscode-autohotkey with MIT License | 6 votes |
public buildBreakPoint(path: string, sourceBreakpoints: DebugProtocol.SourceBreakpoint[], callback: Callback): DebugProtocol.Breakpoint[] {
if (!existsSync(path)) {
return [];
}
const sourceLines = readFileSync(path).toString().split('\n');
const bps = sourceBreakpoints.map((sourceBreakpoint) => {
const breakPoint = new Breakpoint(false, sourceBreakpoint.line, sourceBreakpoint.column, new Source(basename(path), path))
const lineText = sourceLines[sourceBreakpoint.line];
if (lineText && lineText.trim().charAt(0) != ';') {
breakPoint.verified = true;
}
callback(breakPoint)
return breakPoint;
})
this._breakPoints.set(path, bps)
return bps;
}
Example #4
Source File: bundle.ts From luabundler with MIT License | 6 votes |
async run() {
const {args, flags} = this.parse(BundleCommand)
const options: BundleOptions = {
luaVersion: flags.lua,
isolate: flags.isolate,
expressionHandler: (module: Module, expression: Expression) => {
const start = expression.loc!.start
console.warn(`WARNING: Non-literal require found in '${module.name}' at ${start.line}:${start.column}`)
},
}
if (flags.path.length > 0) {
options.paths = flags.path
}
let content
if (!args.file || args.file === '-') {
content = bundleString(await readStdin(), options)
} else {
content = bundle(args.file, options)
}
if (flags.output) {
const resolvedPath = resolvePath(flags.output)
const resolvedDir = dirname(resolvedPath)
if (!existsSync(resolvedDir)) {
mkdirSync(resolvedDir, {recursive: true})
}
writeFileSync(flags.output, content)
} else {
console.log(content)
}
}
Example #5
Source File: test.jest.testRunner.ts From askql with MIT License | 6 votes |
async function runAgainstTestResultFile({
testPath,
name,
runtime,
askJsonTargetPath,
environment,
args,
testResults,
}: AskScriptTestWithResultFileConfig) {
const resultPath = join(testPath, `../${name}.test.result.ts`);
if (existsSync(resultPath)) {
const code = runtime.requireModule<AskCodeOrValue>(askJsonTargetPath);
const result = await runUntyped(environment, code, args);
const expectedResult = runtime.requireModule(resultPath);
const isCorrect = compareAsJson(result, expectedResult);
if ('ASK_PRINT_RESULT' in process.env && process.env.ASK_PRINT_RESULT) {
console.log(`RESULT: ${JSON.stringify(result, null, 2)}`);
}
testResults.computes = assertionResult({
status: isCorrect ? 'passed' : 'failed',
title: 'produces the expected result',
failureMessages: isCorrect
? []
: [
`EXPECTED: ${JSON.stringify(expectedResult, null, 2)}
GOT: ${JSON.stringify(result, null, 2)}`,
],
});
}
}
Example #6
Source File: index.ts From ExpressLRS-Configurator with GNU General Public License v3.0 | 6 votes |
async clearLocks(directory: string): Promise<void> {
const indexLockPath = path.join(directory, '.git', 'index.lock');
if (existsSync(indexLockPath)) {
try {
await fs.unlink(indexLockPath);
} catch (e) {
this.logger.error('failed to clear .git/index.lock', undefined, {
directory,
err: e,
});
}
}
}
Example #7
Source File: init.ts From jmix-frontend with Apache License 2.0 | 6 votes |
function collectGeneratorsFromProject(
clients: GeneratedClientInfo[]
) {
const PROJECT_CLIENTS_RELATIVE_PATH = '../../../../generators';
const projectClientsPath = path.join(__dirname, PROJECT_CLIENTS_RELATIVE_PATH);
if (!fs.existsSync(projectClientsPath)) {
return;
}
collectFromPath(clients, projectClientsPath);
}
Example #8
Source File: session.ts From F95API with MIT License | 6 votes |
//#endregion Getters
/**
* Initializes the session by setting the path for saving information to disk.
*/
constructor(p: string) {
if (!p || p === "") throw new ParameterError("Invalid path for the session file");
this._path = p;
this._isMapped = existsSync(this.path);
this._created = new Date(Date.now());
this._hash = null;
this._token = null;
this._cookieJar = new tough.CookieJar();
}
Example #9
Source File: snapshots-diagnostics-spec.ts From ui5-language-assistant with Apache License 2.0 | 6 votes |
describe(`The language server diagnostics capability`, () => {
// The test files are in the source dir, not lib
const snapshotTestsDir = toSourcesTestDir(__dirname);
const klawItems = klawSync(snapshotTestsDir, { nodir: true });
const inputFiles = filter(klawItems, (item) => {
return item.path.endsWith(INPUT_FILE_NAME);
});
const testDirs = map(inputFiles, (_) => dirname(_.path));
forEach(testDirs, (dirPath) => {
const dirName = basename(dirPath);
// UNCOMMENT THE LINES BELOW AND CHANGE onlyTestDirName TO ONLY RUN A SPECIFIC SNAPSHOT TEST
// const onlyTestDirName = "my-test-dir";
// if (dirName !== onlyTestDirName) {
// return;
// }
const optionsPath = resolve(dirPath, "options.js");
let options: LSPDiagnosticOptions;
if (existsSync(optionsPath)) {
options = require(optionsPath);
} else {
options = { flexEnabled: false };
}
it(`Can create diagnostic for ${dirName.replace(/-/g, " ")} (${relative(
snapshotTestsDir,
dirPath
)})`, async () => {
await snapshotTestLSPDiagnostic(dirPath, options);
});
});
});
Example #10
Source File: spFileHandlers.ts From sourcepawn-vscode with MIT License | 6 votes |
/**
* Recursively read the unparsed includes from a array of Include objects.
* @param {ItemsRepository} itemsRepo The itemsRepository object constructed in the activation event.
* @param {Include[]} includes The array of Include objects to parse.
* @returns void
*/
function readUnscannedImports(
itemsRepo: ItemsRepository,
includes: Include[]
): void {
const debug = ["messages", "verbose"].includes(
Workspace.getConfiguration("sourcepawn").get("trace.server")
);
includes.forEach((include) => {
if (debug) console.log("reading", include.uri.toString());
const filePath = URI.parse(include.uri).fsPath;
if (itemsRepo.fileItems.has(include.uri) || !existsSync(filePath)) {
return;
}
if (debug) console.log("found", include.uri.toString());
let fileItems: FileItems = new FileItems(include.uri);
try {
parseFile(filePath, fileItems, itemsRepo, false, include.IsBuiltIn);
} catch (err) {
console.error(err, include.uri.toString());
}
if (debug) console.log("parsed", include.uri.toString());
itemsRepo.fileItems.set(include.uri, fileItems);
if (debug) console.log("added", include.uri.toString());
readUnscannedImports(itemsRepo, fileItems.includes);
});
}
Example #11
Source File: global.ts From WebCord with MIT License | 6 votes |
export function getAppIcon(sizes:number[]) {
const defaultPath = resolve(getAppPath(), "sources/assets/icons/app.png")
if(existsSync(defaultPath))
return defaultPath;
for (const size of sizes)
if(existsSync("/usr/share/icons/hicolor/"+size.toString()+"x"+size.toString()+"/apps/webcord.png"))
return "/usr/share/icons/hicolor/"+size.toString()+"x"+size.toString()+"/apps/webcord.png";
return "";
}
Example #12
Source File: prerender.ts From ng-event-plugins with Apache License 2.0 | 6 votes |
// Iterate each route path
PRERENDERED_ROUTES.forEach(route => {
const fullPath = join(DEMO_FOLDER, route);
// Make sure the directory structure is there
if (!existsSync(fullPath)) {
mkdirSync(fullPath);
}
// Writes rendered HTML to index.html, replacing the file if it already exists.
previousRender = previousRender
.then(() =>
renderModuleFactory(AppServerModuleNgFactory, {
document: index,
url: route,
extraProviders: [
provideModuleMap(LAZY_MODULE_MAP),
{
provide: APP_BASE_HREF,
useValue: process.env.ORIGIN || localFallback,
},
],
}),
)
.then(html => writeFileSync(join(fullPath, 'index.html'), html));
});
Example #13
Source File: base.provider.ts From nx-extend with MIT License | 6 votes |
public async push(language: string): Promise<void> {
await this.assureRequirementsExists()
if (!existsSync(this.sourceFile)) {
throw new Error('Source file does not exist!')
}
const languageToPush = language || this.config.defaultLanguage
const termsToPush = languageToPush === this.config.defaultLanguage
? this.getSourceTerms()
: this.getLanguageTerms(languageToPush)
if (languageToPush === this.config.defaultLanguage) {
logger.info(`Going to upload ${Object.keys(termsToPush).length} source terms!`)
} else {
logger.info(`Going to upload ${Object.keys(termsToPush).length} terms to "${languageToPush}"!`)
}
await this.uploadTranslations(languageToPush, termsToPush)
}
Example #14
Source File: sourceFilesHelper.ts From elephize with MIT License | 6 votes |
// Try find d.ts source in typescript folder
function getDtsSourceFile(name: string, target?: ScriptTarget) {
if (sourceFiles[name] === undefined) {
let path;
try {
path = name.startsWith('/') ? name : require.resolve('typescript/lib/' + name);
} catch (e) {
path = require.resolve(name.replace(/^node_modules\//, ''));
}
if (existsSync(path)) {
const input = readFileSync(path, { encoding: 'utf-8' });
sourceFiles[name] = createSourceFile(name, input, target!);
} else {
sourceFiles[name] = null;
}
}
return sourceFiles[name];
}
Example #15
Source File: server.ts From svvs with MIT License | 6 votes |
// The Express app is exported so that it can be used by serverless Functions.
export function app(): express.Express {
const server = express()
const distFolder = join(process.cwd(), 'dist/frontend-client/browser')
const indexHtml = existsSync(join(distFolder, 'index.original.html')) ? 'index.original.html' : 'index'
// Our Universal express-engine (found @ https://github.com/angular/universal/tree/master/modules/express-engine)
server.engine('html', ngExpressEngine({
bootstrap: AppServerModule,
}))
server.set('view engine', 'html')
server.set('views', distFolder)
// Example Express Rest API endpoints
// server.get('/api/**', (req, res) => { });
// Serve static files from /browser
server.get('*.*', express.static(distFolder, {
maxAge: '1y',
}))
// All regular routes use the Universal engine
server.get('*', (req, res) => {
res.render(indexHtml, {
req, providers: [
{provide: APP_BASE_HREF, useValue: req.baseUrl},
{provide: REQUEST, useValue: req},
{provide: RESPONSE, useValue: res},
],
})
})
return server
}
Example #16
Source File: utils.ts From HomebridgeMagicHome-DynamicPlatform with Apache License 2.0 | 6 votes |
export function loadJson<T>(file: string, replacement: T): T {
if (!existsSync(file)) {
return replacement;
}
return parseJson<T>(readFileSync(file).toString(), replacement);
}
Example #17
Source File: doxygen.ts From setup-cpp with Apache License 2.0 | 6 votes |
async function activateWinDoxygen() {
switch (process.platform) {
case "win32": {
for (const binDir of [
"C:/ProgramData/chocolatey/bin",
"C:/Program Files/doxygen/bin",
"C:/Program Files (x86)/doxygen",
]) {
if (existsSync(join(binDir, "doxygen.exe"))) {
// eslint-disable-next-line no-await-in-loop
await addPath(binDir)
return binDir
}
}
throw new Error("Failed to find doxygen binary")
}
default: {
throw new Error(`Unsupported platform`)
}
}
}
Example #18
Source File: prerender.ts From fab-menu with MIT License | 6 votes |
// Iterate each route path
ROUTES.forEach(route => {
const fullPath = join(BROWSER_FOLDER, route);
// Make sure the directory structure is there
if (!existsSync(fullPath)) {
mkdirSync(fullPath);
}
// Writes rendered HTML to index.html, replacing the file if it already exists.
previousRender = previousRender
.then(_ =>
renderModuleFactory(AppServerModuleNgFactory, {
document: index,
url: route,
extraProviders: [provideModuleMap(LAZY_MODULE_MAP)]
})
)
.then(html => writeFileSync(join(fullPath, 'index.html'), html));
});
Example #19
Source File: createWskdeployProject.test.ts From openwhisk-vscode-extension with Apache License 2.0 | 6 votes |
suite('templateGenerator.createWskdeployProject', async function () {
test('Create wskdeploy project files', async () => {
const fakeConfirm = sinon.fake.returns(Promise.resolve({ action: 'confirm' }));
sinon.replace(vscode.window, 'showInformationMessage', fakeConfirm);
await createWskdeployProject();
await timeout(1000);
expect(existsSync(MANIFESTFILE_PATH)).to.be.true;
});
test('Show warning message if manifest file exists', async () => {
writeFileSync(MANIFESTFILE_PATH, '');
sinon.spy(vscode.window, 'showErrorMessage');
await createWskdeployProject();
// @ts-ignore
const spyCall = vscode.window.showErrorMessage.getCall(0);
expect(spyCall.args[0].includes('already exists')).to.be.true;
});
afterEach(() => {
rimraf.sync(SRC_DIR_PATH);
rimraf.sync(MANIFESTFILE_PATH);
});
});
Example #20
Source File: evm.ts From airnode with MIT License | 6 votes |
deployContract = async (artifactsFolderPath: string, args: any[] = []) => {
const artifact = getArtifact(artifactsFolderPath);
// Deploy the contract
const contractFactory = new ethers.ContractFactory(artifact.abi, artifact.bytecode, await getUserWallet());
const contract = await contractFactory.deploy(...args);
await contract.deployed();
// Make sure the deployments folder exist
const deploymentsPath = join(__dirname, '../deployments');
if (!existsSync(deploymentsPath)) mkdirSync(deploymentsPath);
// Try to load the existing deployments file for this network - we want to preserve deployments of other contracts
const network = readIntegrationInfo().network;
const deploymentPath = join(deploymentsPath, network + '.json');
let deployment: any = {};
if (existsSync(deploymentPath)) deployment = JSON.parse(readFileSync(deploymentPath).toString());
// The key name for this contract is the path of the artifact without the '.sol' extension
const deploymentName = removeExtension(artifactsFolderPath);
// Write down the address of deployed contract
writeFileSync(deploymentPath, JSON.stringify({ ...deployment, [deploymentName]: contract.address }, null, 2));
return contract;
}
Example #21
Source File: testHelper.ts From cli with Apache License 2.0 | 6 votes |
newCommandHelper() {
return {
deleteSpecFile: () => {
const specficicationFilePath = path.resolve(process.cwd(), 'specification.yaml');
if (existsSync(specficicationFilePath)) {
unlinkSync(specficicationFilePath);
}
}
};
}
Example #22
Source File: key_store.ts From aurora.js with Creative Commons Zero v1.0 Universal | 6 votes |
static loadLocalKeys(env?: KeyStoreEnv): NEAR.keyStores.KeyStore {
const keyStore = new InMemoryKeyStore();
if (env && env.HOME) {
const localValidatorKeyPath = `${env.HOME}/.near/validator_key.json`;
if (existsSync(localValidatorKeyPath)) {
const [accountID, keyPair] = _loadKeyFile(localValidatorKeyPath);
keyStore.setKey('local', accountID, keyPair);
}
}
return keyStore;
}
Example #23
Source File: add-codegen.ts From amplify-codegen with Apache License 2.0 | 6 votes |
export async function testAddCodegen(config: AmplifyFrontendConfig, projectRoot: string, schema: string) {
// init project and add API category
await initProjectWithProfile(projectRoot, { ...config });
const projectName = createRandomName();
await addApiWithoutSchema(projectRoot, { apiName: projectName });
await updateApiSchema(projectRoot, projectName, schema);
const userSourceCodePath = testSetupBeforeAddCodegen(projectRoot, config);
// add codegen succeeds
await expect(addCodegen(projectRoot, { ...config })).resolves.not.toThrow();
// pre-existing file should still exist
expect(existsSync(userSourceCodePath)).toBe(true);
// GraphQL statements are generated
expect(isNotEmptyDir(path.join(projectRoot, config.graphqlCodegenDir))).toBe(true);
testValidGraphQLConfig(projectRoot, config);
}
Example #24
Source File: aws-image-builder-stack.ts From amazon-ec2-image-builder-samples with MIT No Attribution | 6 votes |
getData = (dir: string, file: string) => {
const filePath = path.join(__dirname, "..", dir, file);
if (!existsSync(filePath)) {
Annotations.of(this).addError(
`Component file ${filePath} does not exists`
);
return "";
}
return readFileSync(path.join(__dirname, "..", dir, file)).toString();
};
Example #25
Source File: hardhat.config.ts From balancer-v2-monorepo with GNU General Public License v3.0 | 6 votes |
task('check-deployments', `Check that all tasks' deployments correspond to their build-info and inputs`)
.addOptionalParam('id', 'Specific task ID')
.setAction(async (args: { id?: string; force?: boolean; verbose?: boolean }, hre: HardhatRuntimeEnvironment) => {
// The force argument above is actually not passed (and not required or used in CHECK mode), but it is the easiest
// way to address type issues.
Logger.setDefaults(false, args.verbose || false);
if (args.id) {
await new Task(args.id, TaskMode.CHECK, hre.network.name).run(args);
} else {
const taskDirectory = path.resolve(__dirname, './tasks');
for (const taskID of readdirSync(taskDirectory)) {
const outputDir = path.resolve(taskDirectory, taskID, 'output');
if (existsSync(outputDir) && statSync(outputDir).isDirectory()) {
const outputFiles = readdirSync(outputDir);
if (outputFiles.some((outputFile) => outputFile.includes(hre.network.name))) {
// Not all tasks have outputs for all networks, so we skip those that don't
await new Task(taskID, TaskMode.CHECK, hre.network.name).run(args);
}
}
}
}
});
Example #26
Source File: cli.ts From diablo2 with MIT License | 6 votes |
async function main(): Promise<void> {
if (process.argv.length < 3) {
return usage();
}
const args = process.argv.slice(2);
const isWriteDump = args.indexOf('--dump');
if (isWriteDump > -1) args.splice(isWriteDump, 1);
const localNetworks = findLocalIps();
const networkAdapterIndex = args.findIndex((arg) => localNetworks.find((iface) => iface.interface === arg));
if (networkAdapterIndex == null) {
return usage('Cannot find network adapter');
}
const [networkAdapter] = args.splice(networkAdapterIndex, 1);
Log.debug({ networkAdapter }, 'StartingSniffer');
const gamePath = process.env['DIABLO2_PATH'];
if (gamePath == null || !existsSync(gamePath)) {
Log.error({ gamePath }, 'Path does not exist');
return usage('Cannot find game path, set $DIABLO2_PATH');
}
const sniffer = new Diablo2PacketSniffer(networkAdapter, gamePath);
sniffer.isWriteDump = isWriteDump > 0;
await sniffer.start(Log);
}
Example #27
Source File: invalidPaths.ts From ue4-intellisense-fixes with MIT License | 6 votes |
/**
* *
* @param outPaths
* @param key of outPaths that we're trying to replace, using 'any'. shame...
* @param fromTos reMatch: Regex for matching and replacement of the match, replace: string that replaces the match
*
* @returns true if outPaths modified
*/
function checkAndReplacePathSubstring(outPaths: string[], key: any, ...fromTos: { reMatch: RegExp, replace: string }[]): boolean {
const paths = outPaths;
let currentPath: string = paths[key];
for (const fromTo of fromTos) {
currentPath = currentPath.replace(fromTo.reMatch, fromTo.replace);
}
if (!existsSync(currentPath)) {
return false;
}
else {
paths[key] = currentPath;
return true;
}
}
Example #28
Source File: server.ts From omegga with ISC License | 6 votes |
async getEnvironmentData(): Promise<EnvironmentPreset> {
const saveName =
this._tempSavePrefix + Date.now() + '_' + this._tempCounter.save++;
await this.saveEnvironment(saveName);
const data = this.readEnvironmentData(saveName);
const file = join(this.presetPath, 'Environment', saveName + '.bp');
if (existsSync(file)) unlinkSync(file);
return data;
}
Example #29
Source File: parseCheckovConfig.ts From checkov-vscode with Apache License 2.0 | 6 votes |
getConfigFilePath = (logger: Logger): string | undefined => {
const workspacePath = getWorkspacePath(logger);
if (workspacePath) {
const paths = [path.join(workspacePath, '.checkov.yml'), path.join(workspacePath, '.checkov.yaml')];
for (const path of paths) {
if(existsSync(path)) return path;
}
}
return undefined;
}