當前位置: 首頁>>代碼示例>>TypeScript>>正文


TypeScript fs.promises類代碼示例

本文整理匯總了TypeScript中fs.promises的典型用法代碼示例。如果您正苦於以下問題:TypeScript promises類的具體用法?TypeScript promises怎麽用?TypeScript promises使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


在下文中一共展示了promises類的10個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的TypeScript代碼示例。

示例1: note

async function note(options: Options) {
  if (!options.topic) {
    console.error('No topic given!')
    process.exit(1)
    return
  }

  if (!(await topicExists(options.topic))) {
    console.error(`The topic "${options.topic}" does not exists`)
    process.exit(1)
    return
  }

  const date = new Date()

  const publishedAt = date.toISOString()
  const text = '_Content goes here_'
  const mdx = `---\npublishedAt: ${publishedAt}\n---\n\n${text}\n`

  const dir = await uniqueNote(options.topic, date)
  await fs.promises.mkdir(dir, { recursive: true })

  const file = `${dir}/index.mdx`
  await fs.promises.writeFile(file, mdx)

  console.log(`New note created at: ${file.replace(path.resolve(__dirname, '..'), '')}`)
}
開發者ID:jeremyboles,項目名稱:jeremyboles.com,代碼行數:27,代碼來源:make.ts

示例2: topic

async function topic(options: Options) {
  if (!options.title) {
    console.error('No title given!')
    process.exit(1)
    return
  }

  const topics = path.resolve(__dirname, `../src/topics`)
  const slug = options.slug || makeSlug(options.title)

  const dir = path.join(topics, slug)

  try {
    await fs.promises.access(dir, fs.constants.F_OK)
    console.error(`The topic '${options.title}' already exists`)
    return
  } catch (error) {
    const mdx = `---\ntitle: ${options.title}\ndescription: This is a starter description\n${
      options.topic ? `\nparent: ${options.topic}\n` : ''
    }\ncover:\n  image: full.jpg\n  caption: Starter caption.\n---\n\nSome starter content`

    await fs.promises.mkdir(dir, { recursive: true })

    const file = `${dir}/index.mdx`
    await fs.promises.writeFile(file, mdx)

    console.log(`Created a new topic: ${file.replace(path.resolve(__dirname, '..'), '')}`)
  }
}
開發者ID:jeremyboles,項目名稱:jeremyboles.com,代碼行數:29,代碼來源:make.ts

示例3: getDebugGeneratorContext

// Create a debugging version of our AutoRest abstraction (ideally we'd just
// launch AutoRest and parse the readme.md, but that's also nontrivial to get
// working correctly)
async function getDebugGeneratorContext(swaggerPath : string, outputPath?: string) : Promise<IGeneratorContext> {
    const dir = outputPath || path.dirname(swaggerPath);
    const settings : { [key: string]: any; } = {
        'input-file': swaggerPath,
        'output-folder': dir,
        'clear-output-folder': false,
        'azure-track2-csharp': true
    };
    const ctx = {
        async getSetting(key: string) : Promise<any> { return Promise.resolve(settings[key]); },
        async getInputUris() : Promise<string[]> { return Promise.resolve([swaggerPath]); },
        log(message: string): void { console.log(`INFORMATION: ${message}`); },
        warn(message: string): void { console.error(chalk.yellow(`WARNING: ${message}`)); },
        error(message: string): void { console.error(chalk.red(`ERROR: ${message}`)); },
        verbose(message: string): void { console.log(`VERBOSE: ${message}`); },
        async readFile(filename: string): Promise<string> {
            const data = await fs.promises.readFile(filename);
            return data.toString();
        },
        async writeFile(filename: string, content: string): Promise<void> {
            ctx.verbose(`Emitting file ${filename}`);
            filename = path.join(dir, filename);
            await fs.promises.mkdir(path.dirname(filename), { recursive: true });
            await fs.promises.writeFile(filename, content, 'utf8');
        }
    }
    return ctx;
}
開發者ID:katherinebecker,項目名稱:azure-sdk-for-net,代碼行數:31,代碼來源:interface.ts

示例4: main

async function main() {
  const root = new Root();
  const { resolvePath } = root;
  const numDirectoriesToStrip = 2;
  let initialOrigin: string|null;
  root.resolvePath = (origin, target) => {
    if (!origin) {
      initialOrigin = target;
      for (let i = 0; i <= numDirectoriesToStrip; i++) {
        initialOrigin = path.dirname(initialOrigin);
      }
      return resolvePath(origin, target);
    }
    return path.resolve(initialOrigin!, target);
  };
  const traceProto = await root.load(process.argv[2]);
  const Trace = traceProto.lookupType("Trace");
  const payload = await fs.promises.readFile(process.argv[3]);
  const msg = Trace.decode(payload).toJSON();
  const output = {
    traceEvents: msg.packet
      .filter((packet: any) => !!packet.chromeEvents)
      .map((packet: any) => packet.chromeEvents.traceEvents)
      .map((traceEvents: any) => traceEvents.map((e: any) => {

        const bind_id = (e.flags & (TRACE_EVENT_FLAG_FLOW_IN |
          TRACE_EVENT_FLAG_FLOW_OUT)) ? e.bindId : undefined;
        const scope = (e.flags & TRACE_EVENT_FLAG_HAS_ID) && e.scope ?
            e.scope : undefined;

        return {
          pid: e.processId,
          tid: e.threadId,
          ts: parseIntOrThrow(e.timestamp),
          tts: parseIntOrThrow(e.threadTimestamp),
          ph: String.fromCodePoint(e.phase),
          cat: e.categoryGroupName,
          name: e.name,
          dur: parseIntOrThrow(e.duration),
          tdur: parseIntOrThrow(e.threadDuration),
          bind_id: bind_id,
          flow_in: e.flags & TRACE_EVENT_FLAG_FLOW_IN ? true : undefined,
          flow_out: e.flags & TRACE_EVENT_FLAG_FLOW_OUT ? true : undefined,
          scope: scope,
          id: (e.flags & TRACE_EVENT_FLAG_HAS_ID) ?
              uint64AsHexString(e.id) : undefined,
          args: (e.args || []).reduce((js_args: any, proto_arg: any) => {
            js_args[proto_arg.name] = parseArgValue(proto_arg);
            return js_args;
          }, {})
        };
      }))
      .reduce(flatten, [])
  };
  await fs.promises.writeFile(process.argv[4], JSON.stringify(output, null, 2));
}
開發者ID:v8,項目名稱:v8,代碼行數:56,代碼來源:proto-to-json.ts

示例5: twitter

async function twitter(topic: string, pathname: string) {
  const [_null, username, _type, id] = pathname.split('/')

  const { data } = await axios.get('https://api.twitter.com/1.1/statuses/show.json', {
    headers: { Authorization: `Bearer ${process.env.TWITTER_BEARER_TOKEN}` },
    params: { id },
  })

  const date = dateFns.parse(data.created_at, 'eee MMM dd HH:mm:ss xxxx yyyy', new Date())

  const dir = await uniqueNote(topic, date)
  await fs.promises.mkdir(dir, { recursive: true })

  async function reducer(acc: Promise<string[]>, { media_url_https, type }: { media_url_https: string; type: string }) {
    if (type !== 'photo') return acc

    try {
      const basename = path.basename(media_url_https)
      const image = `${dir}/${basename}`
      const writer = fs.createWriteStream(image)
      const response = await axios.get(media_url_https, { responseType: 'stream' })

      await new Promise((resolve, reject) => {
        response.data.pipe(writer)
        writer.on('error', reject)
        writer.on('finish', resolve)
      })
      return [...(await acc), basename]
    } catch (e) {
      console.error(e)
      return acc
    }
  }

  if (data.entities && data.entities.media) {
    const images = await data.entities.media.reduce(reducer, Promise.resolve([]))
    console.log('Downloaded images attached to this tweet:', images)
  }

  const publishedAt = date.toISOString()
  const text = dePants(data.text)
  const url = `https://twitter.com${pathname}`
  const mdx = `---\npublishedAt: ${publishedAt}\n\ntwitter:\n  url: ${url}\n---\n\n${text}\n`

  const file = `${dir}/index.mdx`
  await fs.promises.writeFile(file, mdx)

  console.log(`Imported tweet to: ${file.replace(path.resolve(__dirname, '..'), '')}`)
}
開發者ID:jeremyboles,項目名稱:jeremyboles.com,代碼行數:49,代碼來源:import.ts

示例6: getSpecificPicture

export async function getSpecificPicture(fileName: string, thumb: boolean = false): Promise<Picture> {
  const splitted = fileName.split('.');
  const type = splitted[splitted.length - 1];
  const filePath = thumb ? `${picturePath}/thumb/${fileName}` : `${picturePath}/${fileName}`;

  try {
    return {
      fileName,
      file: await fs.readFile(path.resolve(filePath)),
      type,
    };
  } catch (e) {
    if (!thumb) {
      throw e;
    }
  }

  const image = await resize({
    src: path.resolve(`${picturePath}/${fileName}`),
    dst: path.resolve(`${picturePath}/thumb/${fileName}`),
    width: 400,
  });
  const file = await fs.readFile(path.resolve(image.path));

  return {
    fileName,
    file,
    type,
  };
}
開發者ID:marudor,項目名稱:randomCats,代碼行數:30,代碼來源:pictures.ts

示例7: savePngDiff

export async function savePngDiff(file: string, png: PNG): Promise<string> {
    const data = PNG.sync.write(png);
    const outputDir = path.resolve(process.cwd(), './build/test-output/integration');
    const diffPath = path.resolve(outputDir, file);

    await fs.mkdir(outputDir, { recursive: true });
    await fs.writeFile(diffPath, data);

    return diffPath;
}
開發者ID:lo1tuma,項目名稱:theorajs,代碼行數:10,代碼來源:files.ts

示例8: prepare_posts

async function prepare_posts() {
  const dir = `${__dirname}/posts/`;
  const folders = await readdir(dir);

  for (const folder of folders) {
    // TODO: Make parallel
    const data = await readFile(`${dir}${folder}/data.json`, "utf8");
    let post_data = JSON.parse(data);

    const post = await readFile(`${dir}${folder}/post.md`, "utf8");
    marked(post, (err, content) => {
      post_data["text"] = content;
      posts[post_data.title.replace(/ /g, "_")] = post_data;
    });
  }
}
開發者ID:hugo19941994,項目名稱:hugofs,代碼行數:16,代碼來源:posts.ts

示例9: getAvailablePictures

async function getAvailablePictures() {
  const rawavailablePictures = await fs.readdir(path.resolve(picturePath));
  const availablePictures = rawavailablePictures.filter(
    fileName => fileName.includes('.') && !fileName.endsWith('.zip')
  );

  return availablePictures;
}
開發者ID:marudor,項目名稱:randomCats,代碼行數:8,代碼來源:pictures.ts

示例10: readOggFile

export async function readOggFile(file: string): Promise<ByteStream> {
    const buffer = await fs.readFile(file);
    const arrayBuffer = buffer.buffer;
    const byteStream = new ByteStream();

    byteStream.setData(arrayBuffer);

    return byteStream;
}
開發者ID:lo1tuma,項目名稱:theorajs,代碼行數:9,代碼來源:files.ts


注:本文中的fs.promises類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。