fs/promises#mkdir TypeScript Examples

The following examples show how to use fs/promises#mkdir. 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 rewind with MIT License 7 votes vote down vote up
// Just keeping it here just in case
async function createFolderIfNotExisting(folderPath: string) {
  try {
    await access(folderPath, constants.R_OK);
  } catch (err) {
    Logger.log(`Could not access the replays folder '${folderPath}'. Creating a new one`);
    // TODO: Access rights?
    return mkdir(folderPath);
  }
}
Example #2
Source File: index.ts    From fetch-gh-release-asset with MIT License 7 votes vote down vote up
baseFetchAssetFile = async (
  octokit: ReturnType<typeof github.getOctokit>,
  { id, outputPath, owner, repo, token }: FetchAssetFileOptions
) => {
  const {
    body,
    headers: { accept, 'user-agent': userAgent },
    method,
    url,
  } = octokit.request.endpoint(
    'GET /repos/:owner/:repo/releases/assets/:asset_id',
    {
      asset_id: id,
      headers: {
        accept: 'application/octet-stream',
      },
      owner,
      repo,
    }
  );
  let headers: HeadersInit = {
    accept,
    authorization: `token ${token}`,
  };
  if (typeof userAgent !== 'undefined')
    headers = { ...headers, 'user-agent': userAgent };

  const response = await fetch(url, { body, headers, method });
  if (!response.ok) {
    const text = await response.text();
    core.warning(text);
    throw new Error('Invalid response');
  }
  const blob = await response.blob();
  const arrayBuffer = await blob.arrayBuffer();
  await mkdir(dirname(outputPath), { recursive: true });
  void (await writeFile(outputPath, new Uint8Array(arrayBuffer)));
}
Example #3
Source File: cache.ts    From cloudmusic-vscode with MIT License 6 votes vote down vote up
static clear(): void {
    rm(MUSIC_CACHE_DIR, { recursive: true })
      .catch(() => undefined)
      .then(() => mkdir(MUSIC_CACHE_DIR, { recursive: true }))
      .catch(() => undefined);
    this._cache.clear();
    this._size = 0;
    while (this._list.length) this._list.pop();
    void this.store();
  }
Example #4
Source File: index.ts    From cloudmusic-vscode with MIT License 6 votes vote down vote up
(async () => {
  Player.init();
  void IPCServer.init();
  void IPCBroadcastServer.init();

  await mkdir(TMP_DIR).catch(() => undefined);
  await mkdir(CACHE_DIR).catch(() => undefined);
  await mkdir(LYRIC_CACHE_DIR).catch(() => undefined);
  await mkdir(MUSIC_CACHE_DIR).catch(() => undefined);
  await MusicCache.init();

  setInterval(
    () => {
      readdir(TMP_DIR)
        .then((files) => {
          for (const file of files) {
            // Playing || Downloading
            if (file === `${Player.id}` || file === `${Player.next?.id || ""}`)
              continue;
            // Remove unused file
            const path = resolve(TMP_DIR, file);
            rm(path).catch(logError);
            // every tick only delete one file
            return;
          }
          // If no files were deleted, the cache can be considered stable
          // In practice, this is mostly invoked every 4 minutes (two ticks)
          void MusicCache.store();
        })
        .catch(logError);
    },
    // Assume the duration of a song is 3.5 minutes
    // Do the cleanup every 2 minutes (2 * 60 * 1000 = 120000)
    120000
  );
})().catch(logError);
Example #5
Source File: file-writer.ts    From xiome with MIT License 6 votes vote down vote up
export function makeFileWriter(root: string) {
	return {
		async write(path: string, html: HtmlTemplate) {
			const path2 = join(root, path)
			await mkdir(dirname(path2), {recursive: true})
			return writeFile(path2, html.toString(), "utf-8")
		}
	}
}
Example #6
Source File: sapio.ts    From sapio-studio with Mozilla Public License 2.0 6 votes vote down vote up
static async new(name: string): Promise<SapioWorkspace> {
        const file = path.join(
            app.getPath('userData'),
            'workspaces',
            name,
            'compiled_contracts'
        );
        const created = await mkdir(file, { recursive: true });
        return new SapioWorkspace(name);
    }
Example #7
Source File: extension.ts    From cloudmusic-vscode with MIT License 5 votes vote down vote up
export async function activate(context: ExtensionContext): Promise<void> {
  /* process.setUncaughtExceptionCaptureCallback(({ message }) =>
    console.error(message)
  ); */
  process.on("unhandledRejection", console.error);
  await mkdir(SETTING_DIR, { recursive: true }).catch();

  context.globalState.setKeysForSync([BUTTON_KEY]);
  AccountViewProvider.context = context;
  AccountManager.context = context;
  ButtonManager.context = context;
  State.context = context;
  Webview.extUri = context.extensionUri;

  // Check mode
  if (!State.wasm) {
    const buildUri = Uri.joinPath(context.extensionUri, "build");
    const files = await workspace.fs.readDirectory(buildUri);
    State.wasm = files.findIndex(([file]) => file === NATIVE_MODULE) === -1;
    if (!State.wasm) State.downInit(); // 3
  }
  console.log("Cloudmusic:", State.wasm ? "wasm" : "native", "mode.");

  const createTreeView = <T>(
    viewId: string,
    treeDataProvider: TreeDataProvider<T>
  ) => window.createTreeView(viewId, { treeDataProvider });

  const queue = createTreeView("queue", QueueProvider.getInstance());
  const local = createTreeView("local", LocalProvider.getInstance());
  const playlist = createTreeView("playlist", PlaylistProvider.getInstance());
  const radio = createTreeView("radio", RadioProvider.getInstance());
  context.subscriptions.push(queue, local, playlist, radio);

  // Only checking the visibility of the queue treeview is enough.
  if (AUTO_START || queue.visible) {
    await realActivate(context);
  } else {
    let done = false;
    const disposables: Disposable[] = [];
    const callback = ({ visible }: TreeViewVisibilityChangeEvent) => {
      if (done || !visible) return;
      done = true;
      void realActivate(context);
      let disposable: Disposable | undefined;
      while ((disposable = disposables.pop())) disposable.dispose();
    };
    disposables.push(queue.onDidChangeVisibility(callback));
  }
}
Example #8
Source File: cache.ts    From cloudmusic-vscode with MIT License 5 votes vote down vote up
static clear(): void {
    rm(LYRIC_CACHE_DIR, { recursive: true })
      .catch(() => undefined)
      .then(() => mkdir(LYRIC_CACHE_DIR, { recursive: true }))
      .catch(() => undefined);
  }
Example #9
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 #10
Source File: shell.ts    From command-bot with Apache License 2.0 5 votes vote down vote up
ensureDir = async (dir: string) => {
  // mkdir doesn't throw an error if the directory already exists
  await mkdir(dir, { recursive: true })
  return dir
}
Example #11
Source File: sapio.ts    From sapio-studio with Mozilla Public License 2.0 5 votes vote down vote up
async contract_output_path(fname: string) {
        const file = this.contract_output_path_name(fname);
        await mkdir(file, { recursive: true });
        return file;
    }
Example #12
Source File: base-generator.ts    From loopback4-microservice-catalog with MIT License 5 votes vote down vote up
async createFolders(names: string[], force = false) {
    for (const name of names) {
      await mkdir(`${join(this.destinationRoot(), name)}`, {
        recursive: force,
      });
    }
  }
Example #13
Source File: main.ts    From hoprnet with GNU General Public License v3.0 4 votes vote down vote up
/*
 * General function to create a libp2p instance to start sending
 * messages to other nodes..
 * @param peerId:PeerId - Identity used by the HOPR node
 * @param options:HoprOptions - Required options to create node
 * @param initialNodes:{ id: PeerId; multiaddrs: Multiaddr[] } - Array of PeerIds w/their multiaddrss
 * @param publicNodesEmitter:PublicNodesEmitter Event emitter for all public nodes.
 * @param isDenied given a peerId, checks whether we want to connect to that node
 * @returns {Hopr} - HOPR node
 */
export async function createLibp2pInstance(
  peerId: PeerId,
  options: HoprOptions,
  initialNodes: { id: PeerId; multiaddrs: Multiaddr[] }[],
  publicNodes: PublicNodesEmitter,
  reviewConnection: AccessControl['reviewConnection']
): Promise<LibP2P> {
  let addressSorter: AddressSorter

  if (options.testing?.preferLocalAddresses) {
    addressSorter = (addrs) => {
      let a = new Array(...addrs) // Create copy to prevent sorting the original array
      return a.sort((aa, ba) => compareAddressesLocalMode(aa.multiaddr, ba.multiaddr))
    }
    log('Preferring local addresses')
  } else {
    // Overwrite address sorter with identity function since
    // libp2p's own address sorter function is unable to handle
    // p2p addresses, e.g. /p2p/<RELAY>/p2p-circuit/p2p/<DESTINATION>
    addressSorter = (addr) => addr
    log('Addresses are sorted by default')
  }

  // Store the peerstore on-disk under the main data path. Ensure store is
  // opened before passing it to libp2p.
  const datastorePath = path.join(options.dataPath, 'peerstore')
  await mkdir(datastorePath, { recursive: true })
  const datastore = new LevelDatastore(datastorePath, { createIfMissing: true })
  await datastore.open()

  log(`using peerstore at ${datastorePath}`)

  const libp2p = await LibP2P.create({
    peerId,
    addresses: { listen: getAddrs(peerId, options).map((x) => x.toString()) },
    // libp2p modules
    modules: {
      transport: [HoprConnect as any],
      streamMuxer: [Mplex],
      connEncryption: [NOISE as any],
      dht: KadDHT
    },
    // Configure peerstore to be persisted using LevelDB, also requires config
    // persistence to be set.
    datastore,
    peerStore: {
      persistence: true
    },
    config: {
      protocolPrefix: `hopr/${options.environment.id}`,
      transport: {
        HoprConnect: {
          config: {
            initialNodes,
            publicNodes,
            environment: options.environment.id,
            allowLocalConnections: options.allowLocalConnections,
            allowPrivateConnections: options.allowPrivateConnections,
            // Amount of nodes for which we are willing to act as a relay
            maxRelayedConnections: 50_000
          },
          testing: {
            // Treat local and private addresses as public addresses
            __useLocalAddresses: options.testing?.announceLocalAddresses,
            // Use local addresses to dial other nodes and reply to
            // STUN queries with local and private addresses
            __preferLocalAddresses: options.testing?.preferLocalAddresses,
            // Prevent nodes from dialing each other directly
            // but allow direct connection towards relays
            __noDirectConnections: options.testing?.noDirectConnections,
            // Do not upgrade to a direct WebRTC connection, even if it
            // is available. Used to test behavior of bidirectional NATs
            __noWebRTCUpgrade: options.testing?.noWebRTCUpgrade,
            // Prevent usage of UPNP to determine external IP address
            __noUPNP: options.testing?.noUPNP
          }
        } as HoprConnectConfig
      },
      dht: {
        enabled: true,
        // Feed DHT with all previously announced nodes
        // @ts-ignore
        bootstrapPeers: initialNodes
      },
      relay: {
        // Conflicts with HoprConnect's own mechanism
        enabled: false
      },
      nat: {
        // Conflicts with HoprConnect's own mechanism
        enabled: false
      }
    },
    dialer: {
      // Use custom sorting to prevent from problems with libp2p
      // and HOPR's relay addresses
      addressSorter,
      // Don't try to dial a peer using multiple addresses in parallel
      maxDialsPerPeer: 1,
      // If we are a public node, assume that our system is able to handle
      // more connections
      maxParallelDials: options.announce ? 250 : 50,
      // default timeout of 30s appears to be too long
      dialTimeout: 10e3
    }
  })

  // Isolate DHTs
  const DHT_WAN_PREFIX = libp2p._dht._wan._protocol
  const DHT_LAN_PREFIX = libp2p._dht._lan._protocol

  if (DHT_WAN_PREFIX !== '/ipfs/kad/1.0.0' || DHT_LAN_PREFIX !== '/ipfs/lan/kad/1.0.0') {
    throw Error(`Libp2p DHT implementation has changed. Cannot set DHT environments`)
  }

  const HOPR_DHT_WAN_PROTOCOL = `/hopr/${options.environment.id}/kad/1.0.0`
  libp2p._dht._wan._protocol = HOPR_DHT_WAN_PROTOCOL
  libp2p._dht._wan._network._protocol = HOPR_DHT_WAN_PROTOCOL
  libp2p._dht._wan._topologyListener._protocol = HOPR_DHT_WAN_PROTOCOL

  const HOPR_DHT_LAN_PROTOCOL = `/hopr/${options.environment.id}/lan/kad/1.0.0`
  libp2p._dht._lan._protocol = HOPR_DHT_LAN_PROTOCOL
  libp2p._dht._lan._network._protocol = HOPR_DHT_LAN_PROTOCOL
  libp2p._dht._lan._topologyListener._protocol = HOPR_DHT_LAN_PROTOCOL

  const onConnectionOriginal = libp2p.upgrader.onConnection
  // check if connection is allowed
  libp2p.upgrader.onConnection = async (conn: Connection) => {
    const allowed = await reviewConnection(conn.remotePeer, 'libp2p peer connect')
    if (allowed) {
      // continue connection
      onConnectionOriginal(conn)
    } else {
      try {
        await conn.close()
      } catch (err: any) {
        log(`Error while closing connection to non-registered node`, err)
      }
    }
  }

  return libp2p
}