fs#PathLike TypeScript Examples

The following examples show how to use fs#PathLike. 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 flatpak-vscode with MIT License 7 votes vote down vote up
export async function appendWatcherExclude(paths: PathLike[]) {
    const config = vscode.workspace.getConfiguration('files')
    const value: Record<string, boolean> = config.get('watcherExclude') || {}

    for (const path of paths) {
        value[path.toString()] = true
    }

    await config.update('watcherExclude', value)
}
Example #2
Source File: render-type.ts    From solita with Apache License 2.0 6 votes vote down vote up
constructor(
    readonly ty: IdlDefinedTypeDefinition,
    readonly fullFileDir: PathLike,
    readonly typeMapper = new TypeMapper()
  ) {
    this.upperCamelTyName = ty.name
      .charAt(0)
      .toUpperCase()
      .concat(ty.name.slice(1))

    this.camelTyName = ty.name.charAt(0).toLowerCase().concat(ty.name.slice(1))
    this.beetArgName = beetVarNameFromTypeName(ty.name)
  }
Example #3
Source File: fs.ts    From playwright-fluent with MIT License 6 votes vote down vote up
getFilesInDirectory = (
  path: PathLike,
  fileFilter?: (path: string) => boolean,
): string[] =>
  readdirSync(path)
    .map((name) => join(path.toString(), name))
    .filter(isFile)
    .filter(ignoreNodeModule)
    .filter(ignoreDotDir)
    .filter(fileFilter || (() => true))
Example #4
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 #5
Source File: render-account.ts    From solita with Apache License 2.0 6 votes vote down vote up
constructor(
    private readonly account: IdlAccount,
    private readonly fullFileDir: PathLike,
    private readonly hasImplicitDiscriminator: boolean,
    private readonly resolveFieldType: ResolveFieldType,
    private readonly typeMapper: TypeMapper,
    private readonly serializers: CustomSerializers
  ) {
    this.upperCamelAccountName = account.name
      .charAt(0)
      .toUpperCase()
      .concat(account.name.slice(1))

    this.camelAccountName = account.name
      .charAt(0)
      .toLowerCase()
      .concat(account.name.slice(1))

    this.accountDataClassName = this.upperCamelAccountName
    this.accountDataArgsTypeName = `${this.accountDataClassName}Args`
    this.beetName = `${this.camelAccountName}Beet`
    this.accountDiscriminatorName = `${this.camelAccountName}Discriminator`

    this.serializerSnippets = this.serializers.snippetsFor(
      this.account.name,
      this.fullFileDir as string,
      this.beetName
    )
  }
Example #6
Source File: profileEVM.ts    From solidity-utils with MIT License 6 votes vote down vote up
export async function profileEVM (txHash: string, instruction: string[], optionalTraceFile?: PathLike | fs.FileHandle) {
    if (!web3.currentProvider || typeof web3.currentProvider === 'string' || !web3.currentProvider.send) {
        throw new Error('Unsupported provider');
    }

    const trace = await promisify(web3.currentProvider.send.bind(web3.currentProvider))({
        jsonrpc: '2.0',
        method: 'debug_traceTransaction',
        params: [txHash, {}],
        id: new Date().getTime(),
    });

    const str = JSON.stringify(trace);

    if (optionalTraceFile) {
        await fs.writeFile(optionalTraceFile, str);
    }

    return instruction.map(instr => {
        return str.split('"' + instr.toUpperCase() + '"').length - 1;
    });
}
Example #7
Source File: render-type.ts    From solita with Apache License 2.0 6 votes vote down vote up
/**
 * Performs parts of the render process that is necessary to determine if the
 * type is fixed or fixable.
 */
export function determineTypeIsFixable(
  ty: IdlDefinedTypeDefinition,
  fullFileDir: PathLike,
  accountFilesByType: Map<string, string>,
  customFilesByType: Map<string, string>
) {
  const typeMapper = new TypeMapper(accountFilesByType, customFilesByType)
  const renderer = new TypeRenderer(ty, fullFileDir, typeMapper)
  return renderer.determineIsFixable()
}
Example #8
Source File: session.ts    From coherence-js-client with Universal Permissive License v1.0 6 votes vote down vote up
/**
   * An internal method to read a cert file given its path.
   *
   * @param certType   the type of the certificate. Used only while creating an error message
   * @param nameOrURL  the path or URL to the cert
   *
   * @returns The {@link Buffer} containing the certificate.
   */
  private static readFile (certType: string, nameOrURL?: PathLike): Buffer {
    if (!nameOrURL) {
      throw new Error('When TLS is enabled, ' + certType + ' cannot be undefined or null')
    }
    return readFileSync(nameOrURL)
  }
Example #9
Source File: file.ts    From estrella with ISC License 6 votes vote down vote up
function sha1(
  filename :PathLike,
  outputEncoding? :crypto.BinaryToTextEncoding,
) :Promise<Buffer|string> {
  return new Promise<Buffer|string>((resolve, reject) => {
    const reader = fs.createReadStream(filename)
    const h = crypto.createHash('sha1')
    reader.on('error', reject)
    reader.on('end', () => {
      h.end()
      resolve(outputEncoding ? h.digest(outputEncoding) : h.digest())
    })
    reader.pipe(h)
  })
}
Example #10
Source File: utils.ts    From flatpak-vscode with MIT License 6 votes vote down vote up
export function generatePathOverride(oldValue: string, prependValues: (PathLike | undefined)[], appendValues: (PathLike | undefined)[]): string {
    return [...prependValues, oldValue, ...appendValues]
        .filter((path) => !!path)  // Filters out empty strings and undefined
        .join(':')
}
Example #11
Source File: fs.ts    From devoirs with MIT License 6 votes vote down vote up
export function readDirectory(path: PathLike): Promise<Dirent[]> {
  return new Promise<Dirent[]>((resolve, reject) => {
    readdir(
      path,
      { withFileTypes: true },
      (error: Error | null, dirents: Dirent[]) => {
        if (error) {
          return reject(error);
        }

        resolve(dirents);
      }
    );
  });
}
Example #12
Source File: mintingAndBurning.ts    From community-repo with GNU General Public License v3.0 6 votes vote down vote up
saveFile = (jsonString: string, path: PathLike) => {
  try {
    fs.rmSync(path);
  } catch (err) {
    console.log("Error deleting file", err);
  }
  try {
    fs.writeFile(path, jsonString, (err) => {
      if (err) {
        console.log("Error writing file", err);
      } else {
        console.log("Successfully wrote file");
      }
    });
  } catch (err) {}
}
Example #13
Source File: file.ts    From estrella with ISC License 6 votes vote down vote up
file.write = async (filename :PathLike, data :string|Uint8Array, options? :FileWriteOptions) => {
  fileModificationLogAppend(filename)
  const opt = options && typeof options == "object" ? options : {}
  try {
    await fsp.writeFile(filename, data, options)
  } catch (err) {
    if (!opt.mkdirOff && err.code == "ENOENT") {
      await file.mkdirs(Path.dirname(String(filename)), opt.mkdirMode)
      await fsp.writeFile(filename, data, options)
    } else {
      throw err
    }
  }
  if (opt.log) {
    let relpath = Path.relative(process.cwd(), String(filename))
    if (relpath.startsWith(".." + Path.sep)) {
      relpath = tildePath(filename)
    }
    log.info(stdoutStyle.green(`Wrote ${relpath}`))
  }
}
Example #14
Source File: index.ts    From quickchart-js with MIT License 5 votes vote down vote up
async toFile(pathOrDescriptor: PathLike | FileHandle): Promise<void> {
    const fs = require('fs');
    const buf = await this.toBinary();
    fs.writeFileSync(pathOrDescriptor, buf);
  }
Example #15
Source File: estrella.d.ts    From estrella with ISC License 5 votes vote down vote up
// chmod edits the mode of a file (synchronous)
// If m is a number, the mode is simply set to m.
// If m is a string or list of strings, the mode is updated using editFileMode.
// Returns the new mode set on file.
// For an asynchronous version, see file.chmod()
export function chmod(file :PathLike, m :number|string|string[]) :number
Example #16
Source File: fs.ts    From playwright-fluent with MIT License 5 votes vote down vote up
isFile = (path: PathLike) => statSync(path).isFile()
Example #17
Source File: profileEVM.ts    From solidity-utils with MIT License 5 votes vote down vote up
export async function gasspectEVM (txHash: string, gasspectOptions: Record<string, unknown> = {}, optionalTraceFile?: PathLike | fs.FileHandle) {
    const options = { ...gasspectOptionsDefault, ...gasspectOptions };

    if (!web3.currentProvider || typeof web3.currentProvider === 'string' || !web3.currentProvider.send) {
        throw new Error('Unsupported provider');
    }

    const trace = await promisify(web3.currentProvider.send.bind(web3.currentProvider))({
        jsonrpc: '2.0',
        method: 'debug_traceTransaction',
        params: [txHash, {}],
        id: new Date().getTime(),
    });

    const ops: Op[] = trace?.result.structLogs;

    const traceAddress = [0, -1];
    for (const [i, op] of ops.entries()) {
        op.traceAddress = traceAddress.slice(0, traceAddress.length - 1);
        _normalizeOp(ops, i);

        if (op.depth + 2 > traceAddress.length) {
            traceAddress[traceAddress.length - 1] += 1;
            traceAddress.push(-1);
        }

        if (op.depth + 2 < traceAddress.length) {
            traceAddress.pop();
        }
    }

    const result = ops.filter(op => op.gasCost > options.minOpGasCost).map(op => op.traceAddress.join('-') + '-' + op.op +
                        (options.args ? '(' + (op.args || []).join(',') + ')' : '') +
                        (options.res ? (op.res ? ':0x' + op.res : '') : '') +
                        ' = ' + op.gasCost);

    if (optionalTraceFile) {
        await fs.writeFile(optionalTraceFile, JSON.stringify(result));
    }

    return result;
}
Example #18
Source File: FileBundle.ts    From arbundles with Apache License 2.0 5 votes vote down vote up
constructor(headerFile: PathLike, txs: PathLike[]) {
    this.headerFile = headerFile;
    this.txs = txs;
  }
Example #19
Source File: mintingAndBurning.ts    From community-repo with GNU General Public License v3.0 5 votes vote down vote up
appentToFile = (line: string, path: PathLike) =>
  fs.appendFileSync(path, line)
Example #20
Source File: index.test.ts    From airnode with MIT License 5 votes vote down vote up
describe('caching utils', () => {
  it('initialises the cache - initPath', () => {
    const mkdirSpy = jest.spyOn(fs, 'mkdirSync');
    mkdirSpy.mockReturnValueOnce('');

    const existsSyncSpy = jest.spyOn(fs, 'existsSync');
    existsSyncSpy.mockReturnValueOnce(false);

    caching.initPath();

    expect(existsSyncSpy).toHaveBeenCalledTimes(1);
    expect(mkdirSpy).toHaveBeenCalledTimes(1);
    expect(mkdirSpy).toHaveBeenCalledWith(CACHE_BASE_PATH);
  });

  it(`adds a key to the cache if it doesn't exist`, () => {
    const writeFileSpy = jest.spyOn(fs, 'writeFileSync');
    writeFileSpy.mockImplementationOnce(() => {});

    const existsSyncSpy = jest.spyOn(fs, 'existsSync');
    existsSyncSpy.mockReset();
    existsSyncSpy.mockReturnValueOnce(false);

    caching.addKey('testKey', 'some data', true);

    expect(existsSyncSpy).toHaveBeenCalledTimes(1);
    expect(writeFileSpy).toHaveBeenCalledTimes(1);
    expect(writeFileSpy).toHaveBeenCalledWith('/tmp/airnode-cache/testKey', `"some data"`);
  });

  it(`sweeps the cache - old files`, () => {
    const files = ['1', '2', '3', '4', '5'];
    const filesStatData = files.map((file) => ({ file, mtimeMs: 1 }));

    const readdirSyncSpy = jest.spyOn(fs, 'readdirSync');
    readdirSyncSpy.mockReturnValueOnce(files as unknown as Dirent[]);

    const statSyncSpy = jest.spyOn(fs, 'statSync');

    statSyncSpy.mockImplementation(
      (file: PathLike) =>
        filesStatData.find((statData) => file.toString().indexOf(statData.file) > -1)! as unknown as Stats
    );

    const rmSyncSpy = jest.spyOn(fs, 'rmSync');
    rmSyncSpy.mockImplementation(() => {});

    caching.sweep();

    expect(readdirSyncSpy).toHaveBeenCalledTimes(1);
    expect(statSyncSpy).toHaveBeenCalledTimes(files.length);
    expect(rmSyncSpy).toHaveBeenCalledTimes(files.length);
  });

  it(`sweeps the cache - no old files present`, () => {
    const files = ['1', '2', '3', '4', '5'];
    const filesStatData = files.map((file) => ({ file, mtimeMs: Date.now() }));

    const readdirSyncSpy = jest.spyOn(fs, 'readdirSync');
    readdirSyncSpy.mockReturnValueOnce(files as unknown as Dirent[]);

    const statSyncSpy = jest.spyOn(fs, 'statSync');

    statSyncSpy.mockImplementation(
      (file: PathLike) =>
        filesStatData.find((statData) => file.toString().indexOf(statData.file) > -1)! as unknown as Stats
    );

    const rmSyncSpy = jest.spyOn(fs, 'rmSync');
    rmSyncSpy.mockImplementation(() => {});

    caching.sweep();

    expect(readdirSyncSpy).toHaveBeenCalledTimes(1);
    expect(statSyncSpy).toHaveBeenCalledTimes(files.length);
    expect(rmSyncSpy).toHaveBeenCalledTimes(0);
  });
});
Example #21
Source File: session.ts    From coherence-js-client with Universal Permissive License v1.0 5 votes vote down vote up
/**
   * The client certificate key.
   */
  private _clientKeyPath?: PathLike
Example #22
Source File: fs.ts    From playwright-fluent with MIT License 5 votes vote down vote up
isDirectory = (path: PathLike) => statSync(path).isDirectory()
Example #23
Source File: paths.ts    From solita with Apache License 2.0 5 votes vote down vote up
constructor(readonly outputDir: PathLike) {}
Example #24
Source File: session.ts    From coherence-js-client with Universal Permissive License v1.0 5 votes vote down vote up
/**
   * The CA certificate paths (separated by ',').
   */
  private _caCertPath?: PathLike