fs#statSync TypeScript Examples

The following examples show how to use fs#statSync. 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 graphql-eslint with MIT License 7 votes vote down vote up
getOnDiskFilepath = (filepath: string): string => {
  try {
    if (statSync(filepath).isFile()) {
      return filepath;
    }
  } catch (err) {
    // https://github.com/eslint/eslint/issues/11989
    if (err.code === 'ENOTDIR') {
      return getOnDiskFilepath(dirname(filepath));
    }
  }

  return filepath;
}
Example #2
Source File: utilsFS.ts    From yfm-transform with MIT License 7 votes vote down vote up
export function isFileExists(file: string) {
    try {
        const stats = statSync(file);

        return stats.isFile();
    } catch (e) {
        return false;
    }
}
Example #3
Source File: artifact.ts    From balancer-v2-monorepo with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Checks that the ABI and bytecode files for `task` matches what is contained in the build-info file.
 * @param task - The task for which to check ABI and bytecode integrity.
 */
export function checkArtifact(task: Task): void {
  const buildInfoDirectory = path.resolve(task.dir(), 'build-info');
  if (existsSync(buildInfoDirectory) && statSync(buildInfoDirectory).isDirectory()) {
    for (const buildInfoFileName of readdirSync(buildInfoDirectory)) {
      const contractName = path.parse(buildInfoFileName).name;

      const expectedArtifact = extractContractArtifact(task, contractName);
      const { abi, bytecode } = readContractABIAndBytecode(task, contractName);

      const bytecodeMatch = bytecode === expectedArtifact.evm.bytecode.object;
      const abiMatch = JSON.stringify(abi) === JSON.stringify(expectedArtifact.abi);
      if (bytecodeMatch && abiMatch) {
        logger.success(`Verified ABI and bytecode integrity of contract '${contractName}' of task '${task.id}'`);
      } else {
        throw Error(
          `The ABI and bytecode for contract '${contractName}' of task '${task.id}' does not match the contents of its build-info`
        );
      }
    }
  }
}
Example #4
Source File: ReaddirRecursive.ts    From yumeko with GNU Affero General Public License v3.0 6 votes vote down vote up
export default function readdirRecursive(directory: string): string[] {
    const results: string[] = [];

    function read(path: string): void {
        const files = readdirSync(path);

        for (const file of files){
            const dir = join(path, file);
            if (statSync(dir).isDirectory()) read(dir);
            else results.push(dir);
        }
    }
    read(directory);

    return results;
}
Example #5
Source File: artifact.ts    From balancer-v2-monorepo with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Read the ABI and bytecode for the contract `contractName` from the ABI and bytecode files.
 */
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function readContractABIAndBytecode(task: Task, contractName: string): { abi: any; bytecode: string } {
  // Read contract ABI from file
  const abiFilePath = path.resolve(task.dir(), 'abi', `${contractName}.json`);
  const abiFileExists = existsSync(abiFilePath) && statSync(abiFilePath).isFile();
  const abi = abiFileExists ? JSON.parse(readFileSync(abiFilePath).toString()) : [];

  // Read contract bytecode from file
  const bytecodeFilePath = path.resolve(task.dir(), 'bytecode', `${contractName}.json`);
  const bytecodeFileExists = existsSync(bytecodeFilePath) && statSync(bytecodeFilePath).isFile();
  const bytecode = bytecodeFileExists ? JSON.parse(readFileSync(bytecodeFilePath).toString()).creationCode : '';
  return { abi, bytecode };
}
Example #6
Source File: add-js-extensions.ts    From blake3 with MIT License 6 votes vote down vote up
function processDir(dir: string): void {
  const entries = readdirSync(dir);
  for (const entry of entries) {
    const path = join(dir, entry);
    if (path.endsWith('.js')) {
      processFile(path);
    } else if (statSync(path).isDirectory()) {
      processDir(path);
    }
  }
}
Example #7
Source File: cleaning.ts    From cli with Apache License 2.0 6 votes vote down vote up
(async () => {
  if (statSync('decrypted', {throwIfNoEntry: false})) {
    restoreCliConfig();
  } else {
    setCliExecPath();
    mkdirSync(SCREENSHOTS_PATH, {recursive: true});
    global.processManager = new ProcessManager();
    process.env.PLATFORM_ENV = process.env.PLATFORM_ENV?.toLowerCase() || '';
    process.env.PLATFORM_HOST = getPlatformHost(process.env.PLATFORM_ENV);
    const chrome = await launchChrome({port: 9222, userDataDir: false});
    await waitOn({resources: ['tcp:9222']});
    const browser = await connectToChromeBrowser();
    await loginWithOffice(browser);
    await chrome.kill();
    await global.processManager.killAllProcesses();
  }
})();
Example #8
Source File: add.ts    From swarm-cli with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public async run(): Promise<void> {
    await super.init()

    if (!this.stamp) {
      this.stamp = await pickStamp(this.beeDebug, this.console)
    }
    const address = new BzzAddress(this.bzzUrl)
    const { node } = await this.initializeNode(address.hash)
    const stat = statSync(this.path)
    const files = await getFiles(this.path)
    for (const file of files) {
      const path = stat.isDirectory() ? join(this.path, file) : this.path
      const { reference } = await this.bee.uploadData(this.stamp, readFileSync(path))
      const remotePath = this.getForkPath(address.path, files, file)
      node.addFork(this.encodePath(remotePath), Buffer.from(reference, 'hex') as Reference)

      if (file === remotePath) {
        this.console.log(chalk.dim(file))
      } else {
        this.console.log(chalk.dim(file + ' -> ' + remotePath))
      }
    }
    await this.saveAndPrintNode(node, this.stamp)
  }
Example #9
Source File: index.ts    From swarm-cli with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
export function fileExists(path: string): boolean {
  try {
    const stat = statSync(path)

    return stat.isFile()
  } catch {
    return false
  }
}
Example #10
Source File: index.ts    From swarm-cli with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
export function directoryExists(path: string): boolean {
  try {
    const stat = statSync(path)

    return !stat.isFile()
  } catch {
    return false
  }
}
Example #11
Source File: index.ts    From swarm-cli with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
export async function getFiles(path: string): Promise<string[]> {
  const stat = statSync(path)

  if (stat.isDirectory()) {
    return await readdirDeepAsync(path, path)
  } else {
    return [path]
  }
}
Example #12
Source File: utilities.ts    From jsonld-lint with Apache License 2.0 6 votes vote down vote up
isDirectory = (fileOrDirectoryPath: string): boolean => {
  const result = statSync(fileOrDirectoryPath);
  return result.isDirectory();
}
Example #13
Source File: get-auto-jsonc-rules-config.ts    From eslint-plugin-jsonc with MIT License 6 votes vote down vote up
/**
 * Checks if the given file name can get the configuration.
 */
function isValidFilename(filename: string) {
    const dir = dirname(filename)
    if (existsSync(dir) && statSync(dir).isDirectory()) {
        if (existsSync(filename) && statSync(filename).isDirectory()) {
            return false
        }
        return true
    }

    return false
}
Example #14
Source File: sep12.ts    From stellar-anchor-tests with Apache License 2.0 6 votes vote down vote up
export function makeSep12Request(requestData: any): Request {
  let requestBody: string | FormData;
  if (hasBinaryFields(requestData.data)) {
    requestBody = new FormData();
    for (const key in requestData.data) {
      if (
        typeof requestData.data[key] === "object" &&
        requestData.data[key].data instanceof ReadStream
      ) {
        const stats = statSync(requestData.data[key].data.path);
        requestBody.append(key, requestData.data[key].data, {
          knownLength: stats.size,
          contentType: requestData.data[key].contentType,
          filename: requestData.data[key].fileName,
        });
      } else if (
        typeof requestData.data[key] === "object" &&
        requestData.data[key].data instanceof Buffer
      ) {
        requestBody.append(key, requestData.data[key].data, {
          knownLength: requestData.data[key].data.length,
          contentType: requestData.data[key].contentType,
          filename: requestData.data[key].fileName,
        });
      } else {
        requestBody.append(key, requestData.data[key]);
      }
    }
  } else {
    requestBody = JSON.stringify(requestData.data);
    requestData.headers["Content-Type"] = "application/json";
  }
  return new Request(requestData.url, {
    method: "PUT",
    headers: requestData.headers,
    body: requestBody,
  });
}
Example #15
Source File: main.ts    From obsidian-jupyter with MIT License 6 votes vote down vote up
async downloadPythonScript() {
		let path = this.getAbsoluteScriptPath();
		try {
			let stats = statSync(path);
			if (!stats.isFile()) {
				throw new Error('python script is missing');
			}
			console.log(`python script exists at ${path}`);
		} catch {
			console.log('downloading missing python script...');
			let client = new HttpClient('obsidian-jupyter');
			let url = `https://github.com/tillahoffmann/obsidian-jupyter/releases/download/${this.manifest.version}/obsidian-jupyter.py`;
			let response = await client.get(url);
			if (response.message.statusCode != 200) {
				throw new Error(`could not download missing python script: ${response.message.statusMessage}`);
			}
			let content = await response.readBody();
			writeFileSync(path, content);
			console.log('obtained missing python script');
		}
	}
Example #16
Source File: code-size.ts    From protobuf-ts with Apache License 2.0 6 votes vote down vote up
testees: Testee[] = readdirSync(testeesPath, {withFileTypes: true})
    .filter(dirent => dirent.isDirectory())
    .filter(dirent => !exclude.includes(dirent.name))
    .map(dirent => {
        const pluginName = dirent.name.split(".")[0];
        return {
            id: dirent.name,
            pluginName,
            pluginPackage: pluginNameToPackageName(pluginName),
            pluginVersion: pluginNameToVersion(pluginName),
            pluginParameter: readFileSync(join(testeesPath, dirent.name, ".plugin-out/parameters.txt"), "utf-8").trim(),
            webpackFileSize: statSync(join(testeesPath, dirent.name, ".webpack-out/index.js")).size,
            webpackLog: readFileSync(join(testeesPath, dirent.name, ".webpack-out/webpack.log"), "utf-8").trim()
        };
    })
    .sort((a, b) => a.webpackFileSize - b.webpackFileSize)
Example #17
Source File: cpGHPages.ts    From fzstd with MIT License 6 votes vote down vote up
git.log({
  from: 'HEAD~1',
  to: 'HEAD'
}).then(async log => {
  const hash = log.latest.hash.slice(0, 7);
  await git.checkout('gh-pages');
  for (const f of readdirSync(to('.'))) {
    if (statSync(f).isFile())
      unlinkSync(to(f));
  }
  const files = readdirSync(to('dist'))
  for (const f of files) {
    copyFileSync(to('dist', f), to(f));
  }
  await git.add(files);
  await git.commit('Build demo from ' + hash);
  await git.checkout('master');
});
Example #18
Source File: hardhat.config.ts    From balancer-v2-monorepo with GNU General Public License v3.0 6 votes vote down vote up
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 #19
Source File: ActionManager.ts    From ts-discord-bot-boilerplate with MIT License 6 votes vote down vote up
/**
     * Parses files into commands from the configured command path.
     * @param {BotClient} client The original client, for access to the configuration.
     * @returns {Collection<string, Command>} A dictionary of every command in a [name, object] pair.
     */
    public initializeCommands(client: BotClient): void {
        const { commands } = client.settings.paths;

        readdir(commands, (err, files) => {
            if (err) Logger.error(err);

            files.forEach(cmd => {
                if (statSync(join(commands, cmd)).isDirectory()) {
                    this.initializeCommands(client);
                } else {
                    const Command: any = require(join(
                        __dirname,
                        '../../',
                        `${commands}/${cmd.replace('ts', 'js')}`
                    )).default;
                    const command = new Command(client);

                    this.commands.set(command.conf.name, command);
                }
            });
        });
    }
Example #20
Source File: init.ts    From jmix-frontend with Apache License 2.0 6 votes vote down vote up
function collectGenerators(generatorsDir: string, genFileName: string = GENERATOR_FILE_NAME): GeneratorInfo[] {
  const dirs = readdirSync(generatorsDir);
  return sortGenerators(dirs.reduce((generators: GeneratorInfo[], name: string) => {
    const generatorPath = path.join(generatorsDir, name);
    if (existsSync(path.join(generatorPath, genFileName)) && statSync(generatorPath).isDirectory()) {
      const generatorExports: GeneratorExports = require(generatorPath);
      if (generatorExports.generator == null) {
        return generators;
      }
      const options = generatorExports.options;
      const params = generatorExports.params;
      const description = generatorExports.description;
      const index = generatorExports.index ?? dirs.length; // will be pushed to a tail if no index

      const iconPath = generatorExports.icon
        ? path.relative(process.cwd(), path.join(generatorPath, generatorExports.icon))
        : undefined;

      generators.push({name, options, params, description, iconPath, index, path: generatorPath});
      return generators;
    } else {
      return generators;
    }
  }, []));
}
Example #21
Source File: Util.ts    From void-wa with GNU General Public License v3.0 6 votes vote down vote up
public readdirRecursive(directory: string): string[] {
        const results: string[] = [];

        function read(path: string): void {
            const files = readdirSync(path);

            for (const file of files) {
                const dir = join(path, file);
                if (statSync(dir).isDirectory()) read(dir);
                else results.push(dir);
            }
        }
        read(directory);

        return results;
    }
Example #22
Source File: config.ts    From vite-tsconfig-paths with MIT License 6 votes vote down vote up
// Adapted from https://github.com/dividab/tsconfig-paths/blob/0b259d4cf6cffbc03ad362cfc6bb129d040375b7/src/tsconfig-loader.ts#L65
function resolveConfigPath(cwd: string) {
  if (statSync(cwd).isFile()) {
    return cwd
  }
  const configPath = walkForTsConfig(cwd)
  if (configPath) {
    return configPath
  }
}
Example #23
Source File: local_path.ts    From ardrive-cli with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Resolves the path, verifies its existance and type to conditionally return its dir and file name
 * @param {string} destOutputPath - the path from where to extract the dir path and name
 * @returns {FilePathAndName} - the directory where to put the file and the file name (which is undefined when the provided destOutputPath is a directory)
 */
export function getOutputFilePathAndName(
	destOutputPath: string,
	fsStatSyncAndPathResolveWrapper = fsStatSyncAndPathResolve
): FilePathAndName {
	const resolvedOutputPath = fsStatSyncAndPathResolveWrapper.resolve(destOutputPath);
	const outputDirname = dirname(resolvedOutputPath);
	const outputBasename = basename(resolvedOutputPath);
	try {
		const outputPathStats = fsStatSyncAndPathResolveWrapper.statSync(resolvedOutputPath);
		// the destination does exist
		if (outputPathStats.isDirectory()) {
			// and is a directory
			return [resolvedOutputPath];
		} else if (outputPathStats.isFile()) {
			// as an existing file
			return [outputDirname, outputBasename];
		}
	} catch (e) {
		// the destination doesn't exist
		const outputParentPathStats = fsStatSyncAndPathResolveWrapper.statSync(outputDirname);
		// the parent exists
		if (outputParentPathStats.isDirectory()) {
			return [outputDirname, outputBasename];
		}
		throw new Error(`The path ${outputDirname} is not a directory!`);
	}
	throw new Error(`The destination is neither a folder nor a file!`);
}
Example #24
Source File: artifact.ts    From balancer-v2-monorepo with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Reads each of the task's build-info files and extract the ABI and bytecode for the matching contract.
 */
export function extractArtifact(task: Task): void {
  const buildInfoDirectory = path.resolve(task.dir(), 'build-info');
  if (existsSync(buildInfoDirectory) && statSync(buildInfoDirectory).isDirectory()) {
    for (const buildInfoFileName of readdirSync(buildInfoDirectory)) {
      const contractName = path.parse(buildInfoFileName).name;
      const artifact = extractContractArtifact(task, contractName);
      writeContractArtifact(task, contractName, artifact);
    }
  }
}
Example #25
Source File: local_path.ts    From ardrive-cli with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Resolves the path, verifies its existance and type to conditionally return its dir and file name
 * @param {string} destOutputPath - the path from where to extract the dir path and name
 * @param fsStatSyncAndPathResolveWrapper - for testing purposes it wraps the fs methods
 * @returns {FilePathAndName} - the directory where to put the file and the file name (which is undefined when the provided destOutputPath is a directory)
 */
export function getOutputFolderPathAndName(
	destOutputPath: string,
	fsStatSyncAndPathResolveWrapper = fsStatSyncAndPathResolve
): FilePathAndName {
	const resolvedOutputPath = fsStatSyncAndPathResolveWrapper.resolve(destOutputPath);
	const outputDirname = dirname(resolvedOutputPath);
	const outputBasename = basename(resolvedOutputPath);
	try {
		const outputPathStats = fsStatSyncAndPathResolveWrapper.statSync(resolvedOutputPath);
		// the destination does exist
		if (outputPathStats.isDirectory()) {
			// TODO: check case sensitivity conflicts here
			// and is a directory
			return [resolvedOutputPath];
		}
	} catch (e) {
		// the destination doesn't exist
		const outputParentPathStats = fsStatSyncAndPathResolveWrapper.statSync(outputDirname);
		// the parent exists
		if (outputParentPathStats.isDirectory()) {
			return [outputDirname, outputBasename];
		}
		// TODO: handle the recoverable error case for `ENAMETOOLONG`
		throw new Error("The destination path doesn't exist"); // TODO: suggest to use the `--create-parents` flag
	}
	throw new Error(`The destination isn't a folder!`);
}
Example #26
Source File: fs.ts    From nx-dotnet with MIT License 5 votes vote down vote up
export function existsSync(path: string) {
  let results;
  try {
    results = statSync(path);
  } catch {}
  return !!results;
}
Example #27
Source File: parentNode.ts    From vscode-ssh with MIT License 5 votes vote down vote up
upload(): any {
        vscode.window.showOpenDialog({ canSelectFiles: true, canSelectMany: false, canSelectFolders: false, openLabel: "Select Upload Path" })
            .then(async uri => {
                if (uri) {
                    const { sftp } = await ClientManager.getSSH(this.sshConfig)
                    const targetPath = uri[0].fsPath;

                    vscode.window.withProgress({
                        location: vscode.ProgressLocation.Notification,
                        title: `Start uploading ${targetPath}`,
                        cancellable:true
                    }, (progress, token) => {
                        return new Promise((resolve) => {
                            const fileReadStream = createReadStream(targetPath)
                            var str = progressStream({
                                length: statSync(targetPath).size,
                                time: 100
                            });
                            let before=0;
                            str.on("progress", (progressData: any) => {
                                if (progressData.percentage == 100) {
                                    resolve(null)
                                    vscode.window.showInformationMessage(`Upload ${targetPath} success, cost time: ${progressData.runtime}s`)
                                    return;
                                }
                                progress.report({ increment: progressData.percentage-before,message:`remaining : ${prettyBytes(progressData.remaining)}` });
                                before=progressData.percentage
                            })
                            str.on("error",err=>{
                                vscode.window.showErrorMessage(err.message)
                            })
                            const outStream = sftp.createWriteStream(this.fullPath + "/" + path.basename(targetPath));
                            fileReadStream.pipe(str).pipe(outStream);
                            token.onCancellationRequested(() => {
                                fileReadStream.destroy()
                                outStream.destroy()
                            });
                        })
                    })

                    // const start = new Date()
                    // vscode.window.showInformationMessage(`Start uploading ${targetPath}.`)
                    // sftp.fastPut(targetPath, this.fullPath + "/" + path.basename(targetPath), err => {
                    //     if (err) {
                    //         vscode.window.showErrorMessage(err.message)
                    //     } else {
                    //         vscode.window.showInformationMessage(`Upload ${this.fullPath} success, cost time: ${new Date().getTime() - start.getTime()}`)
                    //         vscode.commands.executeCommand(Command.REFRESH)
                    //     }
                    // })
                }
            })
    }
Example #28
Source File: file.ts    From a18n with MIT License 5 votes vote down vote up
isFile = (path: string) => {
  try {
    return statSync(path).isFile()
  } catch (e) {
    return false
  }
}
Example #29
Source File: local_path.ts    From ardrive-cli with GNU Affero General Public License v3.0 5 votes vote down vote up
fsStatSyncAndPathResolve = {
	statSync,
	resolve
}