fs/promises#stat TypeScript Examples

The following examples show how to use fs/promises#stat. 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: cache.ts    From cloudmusic-vscode with MIT License 6 votes vote down vote up
static async put(
    key: string,
    name: string,
    path: string,
    md5?: string
  ): Promise<void> {
    try {
      if (!md5 || (await md5File(path)) === md5) {
        const target = resolve(MUSIC_CACHE_DIR, name);
        await copyFile(path, target);
        const { size } = await stat(target);
        this._deleteNode({ key, name });
        this._addNode({ key, name, size });
      }
    } catch {}
  }
Example #2
Source File: arweave-bundle.ts    From metaplex with Apache License 2.0 6 votes vote down vote up
async function getFilePairSize({
  image,
  animation,
  manifest,
}: FilePair): Promise<number> {
  return await [image, animation, manifest].reduce(async (accP, file) => {
    const acc = await accP;
    if (!file) {
      return acc;
    } else {
      const { size } = await stat(file);
      //Adds the 2kb buffer for the txn header and the 10kb min file upload size for bundlr
      return acc + 2000 + Math.max(10000, size);
    }
  }, Promise.resolve(dummyAreaveManifestByteSize));
}
Example #3
Source File: bundles.test.ts    From iuliia-js with MIT License 6 votes vote down vote up
describe("Webpack Tree-Shaking", () => {
    it("should create a tree-shaked bundle with only necesssary schemas included", async () => {
        const bundle = join(webpackConfig.output.path, webpackConfig.output.filename as string);
        await new Promise((res, rej) =>
            webpack(webpackConfig, (err, stats) => (err ? rej(err) : res(stats)))
        );

        const { size } = await stat(bundle);
        expect(size).toBeLessThan(5_700);
        expect(size).toBeGreaterThan(5_000);
        const contents = await readFile(bundle, "utf8");
        const matches = contents.match(/https:\/\/iuliia.ru\/([^/]+)/gim);
        expect(matches).toEqual(["https://iuliia.ru/mosmetro"]);

        const consoleLog = jest.fn();

        runInContext(
            await readFile(bundle, "utf8"),
            createContext({ console: { log: consoleLog } })
        );
        expect(consoleLog).toBeCalledWith("Privet, mir!");
    });
});
Example #4
Source File: db.ts    From hoprnet with GNU General Public License v3.0 5 votes vote down vote up
async init(initialize: boolean, dbPath: string, forceCreate: boolean = false, environmentId: string) {
    let setEnvironment = false

    log(`using db at ${dbPath}`)
    if (forceCreate) {
      log('force create - wipe old database and create a new')
      await rm(dbPath, { recursive: true, force: true })
      await mkdir(dbPath, { recursive: true })
      setEnvironment = true
    }

    let exists = false

    try {
      exists = !(await stat(dbPath)).isDirectory()
    } catch (err: any) {
      if (err.code === 'ENOENT') {
        exists = false
      } else {
        // Unexpected error, therefore throw it
        throw err
      }
    }

    if (!exists) {
      log('db directory does not exist, creating?:', initialize)
      if (initialize) {
        await mkdir(dbPath, { recursive: true })
        setEnvironment = true
      } else {
        throw new Error('Database does not exist: ' + dbPath)
      }
    }
    this.db = levelup(leveldown(dbPath))

    // Fully initialize database
    await this.db.open()

    log(`namespacing db by native address: ${this.id.toCompressedPubKeyHex()}`)
    if (setEnvironment) {
      log(`setting environment id ${environmentId} to db`)
      await this.setEnvironmentId(environmentId)
    } else {
      const hasEnvironmentKey = await this.verifyEnvironmentId(environmentId)

      if (!hasEnvironmentKey) {
        const storedId = await this.getEnvironmentId()

        throw new Error(`invalid db environment id: ${storedId} (expected: ${environmentId})`)
      }
    }
  }
Example #5
Source File: arweave.ts    From metaplex with Apache License 2.0 5 votes vote down vote up
export async function arweaveUpload(
  walletKeyPair,
  anchorProgram,
  env,
  image,
  manifestBuffer, // TODO rename metadataBuffer
  manifest, // TODO rename metadata
  index,
) {
  const imageExt = path.extname(image);
  const fsStat = await stat(image);
  const estimatedManifestSize = estimateManifestSize([
    `${index}${imageExt}`,
    'metadata.json',
  ]);
  const storageCost = await fetchAssetCostToStore([
    fsStat.size,
    manifestBuffer.length,
    estimatedManifestSize,
  ]);
  log.debug(`lamport cost to store ${image}: ${storageCost}`);

  const instructions = [
    anchor.web3.SystemProgram.transfer({
      fromPubkey: walletKeyPair.publicKey,
      toPubkey: ARWEAVE_PAYMENT_WALLET,
      lamports: storageCost,
    }),
  ];

  const tx = await sendTransactionWithRetryWithKeypair(
    anchorProgram.provider.connection,
    walletKeyPair,
    instructions,
    [],
    'confirmed',
  );
  log.debug(`solana transaction (${env}) for arweave payment:`, tx);

  const data = new FormData();
  data.append('transaction', tx['txid']);
  data.append('env', env);
  data.append('file[]', fs.createReadStream(image), {
    filename: `${index}${imageExt}`,
    contentType: `image/${imageExt.replace('.', '')}`,
  });
  data.append('file[]', manifestBuffer, 'metadata.json');

  const result = await upload(data, manifest, index);

  const metadataFile = result.messages?.find(
    m => m.filename === 'manifest.json',
  );
  const imageFile = result.messages?.find(
    m => m.filename === `${index}${imageExt}`,
  );
  if (metadataFile?.transactionId) {
    const link = `https://arweave.net/${metadataFile.transactionId}`;
    const imageLink = `https://arweave.net/${
      imageFile.transactionId
    }?ext=${imageExt.replace('.', '')}`;
    log.debug(`File uploaded: ${link}`);
    return [link, imageLink];
  } else {
    // @todo improve
    throw new Error(`No transaction ID for upload: ${index}`);
  }
}