fs#promises TypeScript Examples

The following examples show how to use fs#promises. 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: utilities.ts    From jsonld-lint with Apache License 2.0 7 votes vote down vote up
getFilesFromDirectory = async (
  directory: string,
  filter: string
): Promise<string[]> => {
  let matchedFiles: string[] = [];
  let files = await promises.readdir(directory);
  for (let i = 0; i < files.length; i++) {
    let filename = path.join(directory, files[i]);
    let stat = await promises.lstat(filename);
    if (stat.isDirectory()) {
      continue;
    } else if (
      filename.indexOf(filter) >= 0 &&
      !matchedFiles.includes(filename)
    ) {
      matchedFiles.push(files[i]);
    }
  }
  return matchedFiles;
}
Example #2
Source File: utils.ts    From adonis5-scheduler with MIT License 7 votes vote down vote up
export async function getSchedulerTmpPath() {
	const path = join(process.cwd(), 'tmp')
	try {
		if (!(await dirIsExists(path))) {
			await promises.mkdir(path)
		}
	} catch (e) {
		console.error(e.message)
	}
	return path
}
Example #3
Source File: utilities.ts    From jsonld-lint with Apache License 2.0 7 votes vote down vote up
lintFile = async (file: string): Promise<boolean> => {
  const filePath = path.join(process.env.PWD as string, file);
  const fileContents = (await promises.readFile(filePath)).toString();
  const results = await jsonldLint(fileContents);
  if (results.length > 0) {
    formatResults(filePath, results);
    return true;
  } else {
    console.log(`SUCCESS: ${filePath}`);
  }
  return false;
}
Example #4
Source File: file.service.ts    From kontent-backup-manager-js with MIT License 6 votes vote down vote up
async loadFileAsync(fileNameWithoutExtension: string): Promise<Buffer> {
        const filePath = this.getFilePath(fileNameWithoutExtension);

        if (this.config.enableLog) {
            console.log(`Reading file '${filePath}'`);
        }
        const file = await promises.readFile(filePath);
        if (this.config.enableLog) {
            console.log(`Reading file completed`);
        }

        return file;
    }
Example #5
Source File: GenGenCodeGen.ts    From gengen with MIT License 6 votes vote down vote up
protected copyLibs(settings: IOptions): void {
        const output = settings.output;
        promises.copyFile(resolve(__dirname, '../../libs/types.ts'), `${output}/types.ts`);
        promises.copyFile(resolve(__dirname, '../../libs/Guid.ts'), `${output}/Guid.ts`);
        promises.copyFile(resolve(__dirname, '../../libs/utils.ts'), `${output}/utils.ts`);
        promises.copyFile(resolve(__dirname, '../../libs/mappers.ts'), `${output}/mappers.ts`);
        promises.copyFile(resolve(__dirname, '../../libs/date-converters.ts'), `${output}/date-converters.ts`);
        promises.copyFile(resolve(__dirname, '../../libs/base-http.service.ts'), `${output}/base-http.service.ts`);
        promises.copyFile(resolve(__dirname, '../../libs/download.service.ts'), `${output}/download.service.ts`);
    }
Example #6
Source File: EmailTemplateLoader.ts    From ZenTS with MIT License 6 votes vote down vote up
public async load(): Promise<EmailTemplates> {
    const emailTemplates = new Map() as EmailTemplates
    const emailFilesPath = fs.resolveZenPath('email')

    if (!((await fs.exists(emailFilesPath)) || config.email.engine === 'plain')) {
      return emailTemplates
    }

    const filePaths = await this.loadFiles(emailFilesPath)

    for (const filePath of filePaths) {
      const { name } = parse(filePath)
      const content = await promises.readFile(filePath, {
        encoding: 'utf-8',
      })

      emailTemplates.set(name, content)
    }

    return emailTemplates
  }
Example #7
Source File: file-manager.ts    From open-design-sdk with Apache License 2.0 6 votes vote down vote up
async saveTextFile(
    filePath: string,
    content: string,
    options: {
      cancelToken?: CancelToken | null
    } = {}
  ): Promise<void> {
    const cancelToken = createCancelToken.race([
      options.cancelToken,
      this._destroyTokenController.token,
    ])

    const filename = this._resolvePath(filePath)
    await promises.writeFile(filename, content)

    cancelToken.throwIfCancelled()
  }
Example #8
Source File: gcp-cache.ts    From nx-extend with MIT License 6 votes vote down vote up
private async uploadDirectory(cacheDirectory: string, dir: string) {
    for (const entry of await promises.readdir(dir)) {
      const full = join(dir, entry)
      const stats = await promises.stat(full)

      if (stats.isDirectory()) {
        await this.uploadDirectory(cacheDirectory, full)

      } else if (stats.isFile()) {
        const destination = relative(cacheDirectory, full)
        this.uploadQueue.push(this.bucket.upload(full, { destination }))
      }
    }
  }
Example #9
Source File: write.ts    From mercurius-typescript with MIT License 6 votes vote down vote up
/**
 * Write the target file only if the content changed,
 * It always returns the target path
 */
export async function writeFileIfChanged(targetPath: string, content: string) {
  const fileExists = existsSync(targetPath)

  if (fileExists) {
    const existingContent = await promises.readFile(targetPath, {
      encoding: 'utf-8',
    })

    if (existingContent === content) return targetPath
  }

  await promises.writeFile(targetPath, content, {
    encoding: 'utf-8',
  })

  return targetPath
}
Example #10
Source File: utilities.ts    From jsonld-lint with Apache License 2.0 6 votes vote down vote up
processFile = async (file: string): Promise<boolean> => {
  const filePath = path.join(process.env.PWD as string, file);
  const fileContents = (await promises.readFile(filePath)).toString();
  const results = await processDocument(fileContents);
  console.log(JSON.stringify(results, null, 2));
  return false;
}
Example #11
Source File: utils.ts    From adonis5-scheduler with MIT License 6 votes vote down vote up
listFiles = (path: string): Promise<string[]> => {
	return promises.readdir(path)
}
Example #12
Source File: index.ts    From swarm-cli with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Lists all files recursively in a folder
 * @param path folder path
 * @returns an async generator of path strings
 */
async function* walkTreeAsync(path: string): AsyncGenerator<string> {
  for await (const entry of await promises.opendir(path)) {
    const entryPath = join(path, entry.name)

    if (entry.isDirectory()) {
      yield* walkTreeAsync(entryPath)
    } else if (entry.isFile()) {
      yield entryPath
    }
  }
}
Example #13
Source File: fsHelper.ts    From vscode-lean4 with Apache License 2.0 6 votes vote down vote up
/**
    Helper used to replace fs.existsSync (using existsSync to check for the existence
    of a file before calling fs.open(), fs.readFile() or fs.writeFile() is not recommended.
    Doing so introduces a race condition, since other processes may change the file's state between the two calls.
    Instead, user code should open/read/write the file directly and handle the error raised if the file does not exist.)
    param: pathFile - A string representing a PathLike

    returns Promise<boolean> that represents if a file exist
**/
export async function fileExists(pathFile: PathLike): Promise<boolean> {
    return await promises.access(pathFile).then(() => true, () => false);
}
Example #14
Source File: utilities.ts    From jsonld-lint with Apache License 2.0 6 votes vote down vote up
readFile = async (
  directory: string,
  file: string
): Promise<string> => {
  const directoryPath = path.join(process.env.PWD as string, directory);
  const filePath = path.join(directoryPath, file);
  return (await promises.readFile(filePath)).toString();
}
Example #15
Source File: fs_extensions.ts    From Creators.TF-Community-Launcher with MIT License 6 votes vote down vote up
/**
     * moves a file to a new location
     * returns if oldPath is not a file
     * creates directories if needed
     * @param {string} oldPath origin path
     * @param {string} newPath destination path
     */
    public static async move(oldPath: string, newPath: string): Promise<string> {
        if (!await this.fileExists(oldPath)) {
            return;
        }
        const newDirectory = path.dirname(newPath);
        await this.ensureDirectoryExists(newDirectory);

        await promises.rename(oldPath, newPath);
    }
Example #16
Source File: collectCoverage.ts    From Assistive-Webdriver with MIT License 6 votes vote down vote up
export async function collectCoverage(url: string) {
  if (process.env.ENABLE_COVERAGE === "1") {
    try {
      const response = await fetch(`${url}/__coverage__`);
      if (response.ok) {
        const json = await response.buffer();
        const nycFolder = join(process.cwd(), ".nyc_output");
        await promises.mkdir(nycFolder, { recursive: true });
        const fileName = join(nycFolder, `${createUUID()}.json`);
        await promises.writeFile(fileName, json);
        info(`Successfully saved code coverage from the VM in ${fileName}.`);
      } else {
        warn(`Code coverage does not seem to be enabled in the VM.`);
      }
    } catch (error) {
      warn(`Failed to collect/save code coverage from the VM`, error);
    }
  }
}
Example #17
Source File: Statuspage.ts    From discord-statuspage-v2 with MIT License 6 votes vote down vote up
/**
   * Run at a specified interval
   */
  run (): void {
    promises.stat(this.options.file)
      .catch(async (err) => {
        if (err.code === 'ENOENT') await promises.writeFile(this.options.file, '{}')
      })

    this.emit('start', { startedAt: new Date() })

    const run = async (): Promise<void> => {
      this.emit('run', { time: new Date() })
      await this.fetch()
      await this.read()

      if (this.compare()) {
        this.write()
        this.emit('update', this.local)
      }
    }

    run()
    setInterval(run, this.options.interval)
  }
Example #18
Source File: FileSessionStoreAdapter.ts    From ZenTS with MIT License 6 votes vote down vote up
public async remove(sessionId: string): Promise<void> {
    const filePath = this.getFilePath(sessionId)

    if (!(await fs.exists(filePath))) {
      return
    }

    try {
      await promises.unlink(filePath)
    } catch (e) {
      log.error(e)
    }
  }
Example #19
Source File: config.ts    From Creators.TF-Community-Launcher with MIT License 6 votes vote down vote up
//This attempts to find the users tf2 directory automatically.
    public static async GetTF2Directory(steamdir: string): Promise<string> {
        let tf2Path = "steamapps/common/Team Fortress 2/";

        //Check if tf2 is installed in the steam installation steamapps.
        if (await FsExtensions.pathExists(path.join(steamdir, tf2Path))) {
            tf2Path = path.join(steamdir, tf2Path);
            return tf2Path;
        } else {
            //Check the library folders file and check all those for the tf2 directory.
            const libraryFolders = `${steamdir}/steamapps/libraryfolders.vdf`;
            if (await FsExtensions.pathExists(libraryFolders)) {
                //How this works:
                //Read the lines of the libraryfolders
                //If we find a match with the regular expression, we have a possible other library folder.
                //We check this library folder to see if it has a tf2 install folder.
                //If yes, we use this!
                //If no, we just fail.

                const data = await promises.readFile(libraryFolders, "utf8");
                const lines = data.split("\n");
                for (let i = 0; i < lines.length; i++) {
                    const result = pathStringRegex.exec(lines[i]);
                    if (result) {
                        if (result[2]) {
                            const potentialPath = path.join(result[2], "/", tf2Path);
                            if (await FsExtensions.pathExists(potentialPath)) {
                                return potentialPath;
                            }
                        }
                    }
                }
                throw new Error("No other tf2 libraries had TF2");
            } else {
                throw new Error("TF2 not found in base install location, no other libraries found.");
            }
        }
    }
Example #20
Source File: FS.ts    From ZenTS with MIT License 6 votes vote down vote up
public static async exists(pathToDirOrFile: string): Promise<boolean> {
    let success = true

    try {
      await promises.access(pathToDirOrFile)
    } catch (error) {
      success = false
    }

    return success
  }
Example #21
Source File: fs_extensions.ts    From Creators.TF-Community-Launcher with MIT License 6 votes vote down vote up
/**
     * creates directory, if it does not exist
     * does nothing otherwise
     * @param {string} directory directory to check
     * @returns {Promise<boolean>} true if directory was created, otherwise false
     */
    public static async ensureDirectoryExists(directory: string): Promise<boolean> {
        if(!await this.pathExists(directory)){
            await promises.mkdir(directory, {recursive: true});
            log.log("Created the directory: " + directory);
            return true;
        }
        return false;
    }
Example #22
Source File: FS.ts    From ZenTS with MIT License 6 votes vote down vote up
public static async readJson<T>(filePath: string): Promise<T> {
    let json = null

    try {
      const content = await promises.readFile(filePath, {
        encoding: 'utf-8',
      })
      json = JSON.parse(content) as T
    } catch (e) {
      log.error(e)
    }

    return json
  }
Example #23
Source File: deploy.ts    From perpetual-protocol with GNU General Public License v3.0 5 votes vote down vote up
{ readdir } = promises
Example #24
Source File: fs.ts    From osmosfeed with MIT License 5 votes vote down vote up
copyFileAsync = promises.copyFile
Example #25
Source File: update.ts    From gitmars with GNU General Public License v3.0 5 votes vote down vote up
async function run() {
    await updatePackageJSON()
    await promises.copyFile('./CONTRIBUTING.md', './packages/contributing.md')
    execSync('pnpm run prettier')
}
Example #26
Source File: Application.ts    From discord-qt with GNU General Public License v3.0 5 votes vote down vote up
{ readdir } = promises
Example #27
Source File: build.ts    From gitmars with GNU General Public License v3.0 5 votes vote down vote up
async function buildMetaFiles() {
    for (const { name } of packages) {
        const packageRoot = path.resolve(__dirname, '..', 'packages', name)
        const packageDist = path.resolve(packageRoot, 'dist')

        if (name === 'core')
            await promises.copyFile(
                path.join(rootDir, 'README.md'),
                path.join(packageDist, 'README.md')
            )

        for (const file of FILES_COPY_ROOT)
            await promises.copyFile(
                path.join(rootDir, file),
                path.join(packageDist, file)
            )

        const files = await fg(FILES_COPY_LOCAL, { cwd: packageRoot })
        for (const file of files)
            await promises.copyFile(
                path.join(packageRoot, file),
                path.join(packageDist, file)
            )

        const packageJSON = JSON.parse(
            readFileSync(path.join(packageRoot, 'package.json'), 'utf8')
        )
        for (const key of Object.keys(packageJSON.dependencies || {})) {
            if (key.startsWith('@gitmars/'))
                packageJSON.dependencies[key] = version
        }
        for (const key of Object.keys(packageJSON.devDependencies || {})) {
            if (key.startsWith('@gitmars/'))
                packageJSON.devDependencies[key] = version
        }
        writeFileSync(
            path.join(packageDist, 'package.json'),
            JSON.stringify(packageJSON, null, 4)
        )
    }
}
Example #28
Source File: OsuDBDao.ts    From rewind with MIT License 5 votes vote down vote up
{ readFile } = promises
Example #29
Source File: impl.ts    From kassette with MIT License 5 votes vote down vote up
public async init() {
    const { root, tlsCAKeyPath } = this._config;
    const tlsCAFilePath = tlsCAKeyPath ? resolve(root, tlsCAKeyPath) : null;
    if (tlsCAFilePath) {
      try {
        let ca: pki.Certificate | undefined;
        let key: pki.PrivateKey | undefined;
        let extraItems = 0;
        const content = await promises.readFile(tlsCAFilePath, 'utf8');
        for (const object of pem.decode(content)) {
          const isCertificate =
            object.type === 'CERTIFICATE' ||
            object.type === 'X509 CERTIFICATE' ||
            object.type === 'TRUSTED CERTIFICATE';
          const isPrivateKey = object.type === 'PRIVATE KEY' || object.type === 'RSA PRIVATE KEY';
          const body = asn1.fromDer(object.body);
          if (isCertificate && !ca) {
            ca = pki.certificateFromAsn1(body);
          } else if (isPrivateKey && !key) {
            key = pki.privateKeyFromAsn1(body);
          } else {
            extraItems++;
          }
        }
        if (!ca || !key || extraItems > 0) {
          throw new Error(
            `${tlsCAKeyPath} should contain exactly one certificate and one private key.`,
          );
        }
        ca.privateKey = key;
        this._caObject = ca;
        this._caPem = pki.certificateToPem(ca);
      } catch (error) {
        if (error.code !== 'ENOENT') {
          throw error;
        }
      }
    }
    if (!this._caObject) {
      const ca = await createCertificate(['DO NOT TRUST kassette TLS interception certificate'], {
        keySize: this._config.tlsKeySize,
      });
      this._caObject = ca.object;
      this._caPem = ca.cert;
      if (tlsCAFilePath) {
        await promises.writeFile(tlsCAFilePath, `${ca.cert}\n${ca.key}`);
      }
    }
  }