• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

TypeScript fs-extra.readFile函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了TypeScript中fs-extra.readFile函数的典型用法代码示例。如果您正苦于以下问题:TypeScript readFile函数的具体用法?TypeScript readFile怎么用?TypeScript readFile使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了readFile函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的TypeScript代码示例。

示例1: def

    def('should create a .pfx file', async () => {
      await fs.copy(
        join(__dirname, '../../../api/core/test/fixture', 'bogus-private-key.pvk'),
        join(tmpDir, 'dummy.pvk'),
      );
      const outputCertPath = await createDefaultCertificate('CN=Test', {
        certFilePath: tmpDir,
        certFileName: 'dummy',
        install: false,
      });

      const fileContents = await fs.readFile(outputCertPath);
      expect(fileContents).to.be.an.instanceof(Buffer);
      expect(fileContents.length).to.be.above(0);
    });
开发者ID:balloonzzq,项目名称:electron-forge,代码行数:15,代码来源:MakerAppX_spec.ts


示例2: it

 it('should accept a custom downloader', async () => {
   const zipPath = await download('2.0.3', {
     cacheRoot,
     unsafelyDisableChecksums: true,
     downloader: {
       async download(url, targetPath) {
         expect(
           url.replace(process.platform, 'platform').replace(process.arch, 'arch'),
         ).toMatchSnapshot();
         await fs.writeFile(targetPath, 'faked from downloader');
       },
     },
   });
   expect(await fs.readFile(zipPath, 'utf8')).toEqual('faked from downloader');
 });
开发者ID:electron-userland,项目名称:electron-download,代码行数:15,代码来源:index.spec.ts


示例3: ignoreNodeModules

export async function ignoreNodeModules(ignoreFile: string) {
  let ignoreLines: string[] = [];
  if (await fse.pathExists(ignoreFile)) {
    const content = await fse.readFile(ignoreFile, 'utf-8');
    ignoreLines = content.split(EOL);
  }
  const hasNodeModules = ignoreLines.some((line) => {
    return searchNodeModulesLine.test(line);
  });
  if (hasNodeModules) {
    return;
  }
  ignoreLines.push(nodeModulesLine);
  const outContent = ignoreLines.join(EOL) + EOL;
  await fse.writeFile(ignoreFile, outContent);
}
开发者ID:,项目名称:,代码行数:16,代码来源:


示例4: join

 const check = (root: string) => {
     const path = join(root, url);
     readFile(path).then((file: Buffer) => {
         res.setHeader('Cache-Control', 'public, max-age=31557600');
         res.writeHead(200, { 'Content-Type': contentType });
         res.end(file);
     })
         .catch(() => {
             if (ROOTS.length) {
                 check(ROOTS.pop());
             } else {
                 res.writeHead(404, { 'Content-Type': 'text/plain' });
                 res.end('404 Not Found\n');
             }
         });
 };
开发者ID:beregovoy68,项目名称:WavesGUI,代码行数:16,代码来源:utils.ts


示例5: withTempDirectory

        await withTempDirectory(async (dir2) => {
          const secondAppPath = await copyApp(dir2, 'update')
          const appPJPath = path.resolve(secondAppPath, 'Contents', 'Resources', 'app', 'package.json')
          await fs.writeFile(
            appPJPath,
            (await fs.readFile(appPJPath, 'utf8')).replace('1.0.0', '2.0.0')
          )
          await signApp(secondAppPath)
          const updateZipPath = path.resolve(dir2, 'update.zip');
          await spawn('zip', ['-r', '--symlinks', updateZipPath, './'], {
            cwd: dir2
          })

          server.get('/update-file', (req, res) => {
            res.download(updateZipPath)
          })
          server.get('/update-check', (req, res) => {
            res.json({
              url: `http://localhost:${port}/update-file`,
              name: 'My Release Name',
              notes: 'Theses are some release notes innit',
              pub_date: (new Date()).toString()
            })
          })
          const relaunchPromise = new Promise((resolve, reject) => {
            server.get('/update-check/updated/:version', (req, res) => {
              res.status(204).send()
              resolve()
            })
          })
          const launchResult = await launchApp(appPath, [`http://localhost:${port}/update-check`])
          logOnError(launchResult, () => {
            expect(launchResult).to.have.property('code', 0)
            expect(launchResult.out).to.include('Update Downloaded')
            expect(requests).to.have.lengthOf(2)
            expect(requests[0]).to.have.property('url', '/update-check')
            expect(requests[1]).to.have.property('url', '/update-file')
            expect(requests[0].header('user-agent')).to.include('Electron/')
            expect(requests[1].header('user-agent')).to.include('Electron/')
          })

          await relaunchPromise
          expect(requests).to.have.lengthOf(3)
          expect(requests[2]).to.have.property('url', '/update-check/updated/2.0.0')
          expect(requests[2].header('user-agent')).to.include('Electron/')
        })
开发者ID:doridoridoriand,项目名称:electron,代码行数:46,代码来源:api-autoupdater-darwin-spec.ts


示例6: it

  it('can process a successful merge result', async () => {
    const relativePath = Path.join(
      __dirname,
      '../../fixtures/merge-parser/desktop/valid-merge-master-into-script-upgrade.txt'
    )
    const filePath = Path.resolve(relativePath)
    const input = await FSE.readFile(filePath, { encoding: 'utf8' })

    const result = parseMergeResult(input)
    expect(result.kind).equals('Success')

    const mergeResult = result as IMergeSuccess
    expect(mergeResult.entries.length).equals(21)
    mergeResult.entries.forEach(e => {
      expect(e.diff).not.equal('')
    })
  })
开发者ID:soslanashkhotov,项目名称:desktop,代码行数:17,代码来源:parse-merge-result-test.ts


示例7: parse

export function parse(p: string, property: string): Promise<string> {
  const pl = path.join(p, 'Contents', 'Info.plist')
  log('reading property file "%s"', pl)

  const failed = (e: Error) => {
    const msg = `Info.plist not found: ${pl}
    ${e.message}`
    log('could not read Info.plist for %s', pl)
    throw notInstalledErr('', msg)
  }

  return fs
    .readFile(pl, 'utf8')
    .then(plist.parse)
    .then(prop(property))
    .then(String) // explicitly convert value to String type
    .catch(failed) // to make TS compiler happy
}
开发者ID:YOU54F,项目名称:cypress,代码行数:18,代码来源:util.ts


示例8: prepareHTML

export function prepareHTML(param: IPrepareHTMLOptions): Promise<string> {
    const filter = moveTo(param.target);

    return Promise.all([
        readFile(join(__dirname, '../src/index.html'), 'utf8'),
        readJSON(join(__dirname, '../package.json')),
        readJSON(join(__dirname, './meta.json'))
    ])
        .then((data) => {
            const [file, pack, meta] = data;
            const connectionTypes = ['mainnet', 'testnet'];

            if (!param.scripts) {
                const sourceFiles = getFilesFrom(join(__dirname, '../src'), '.js', function (name, path) {
                    return !name.includes('.spec') && !path.includes('/test/');
                });
                param.scripts = meta.vendors.map((i) => join(__dirname, '..', i)).concat(sourceFiles);
                param.scripts.push(join(__dirname, '../loginDaemon.js'));
            }

            if (!param.styles) {
                param.styles = meta.stylesheets.map((i) => join(__dirname, '..', i)).concat(getFilesFrom(join(__dirname, '../src'), '.less'));
            }

            const networks = connectionTypes.reduce((result, item) => {
                result[item] = meta.configurations[item];
                return result;
            }, Object.create(null));

            return compile(file)({
                pack: pack,
                domain: meta.domain,
                build: {
                    type: 'web'
                },
                network: networks[param.connection]
            });
        })
        .then((file) => {
            return replaceStyles(file, param.styles.map(filter).map(s => `/${s}`));
        }).then((file) => {
            return replaceScripts(file, param.scripts.map(filter));
        });
}
开发者ID:beregovoy68,项目名称:WavesGUI,代码行数:44,代码来源:utils.ts


示例9: renderTemplate

async function renderTemplate({task, numCompleted, numTotal}: TaskStats) {
  const template = await fs.readFile(templateFile, {encoding: 'utf8'});
  const fullDict = {};
  for (const k in task) {
    fullDict[k] = utils.htmlEntities(task[k]);
  }
  // Note: these two fields are not available in mechanical turk.
  fullDict['ALL_JSON'] = utils.htmlEntities(JSON.stringify(task, null, 2));
  fullDict['ALL_JSON_RAW'] = JSON.stringify(task);
  const userHtml = utils.renderTemplate(template, fullDict);

  const thisFlash = flash;
  flash = '';

  const sourceInputs = _.map(task, (v, k) =>
      `<input type=hidden name="${k}" value="${utils.htmlEntities(v)}">`
    ).join('\n');

  return utils.dedent`
    <!doctype html>
    <html>
    <title>${numCompleted} / ${numTotal} - localturk</title>
    <body><form action=/submit method=post>
    <p>${numCompleted} / ${numTotal} <span style="background: yellow">${thisFlash}</span></p>
    ${sourceInputs}
    ${userHtml}
    <hr/><input type=submit />
    </form>
    <script>
    // Support keyboard shortcuts via, e.g. <.. data-key="1" />
    window.addEventListener("keydown", function(e) {
      if (document.activeElement !== document.body) return;
      var key = e.key;
      const el = document.querySelector('[data-key="' + key + '"]');
      if (el) {
        e.preventDefault();
        el.click();
      }
    });
    </script>
    </body>
    </html>
  `;
}
开发者ID:danvk,项目名称:localturk,代码行数:44,代码来源:localturk.ts


示例10: reject

    return new Promise<userAccountData[]>((resolve, reject) => {
        if (useCredentials) {
            fs.readFile(path.join(steamDirectory, 'config', 'loginusers.vdf'), 'utf8', (err, data) => {
                try {
                    if (err && err.code !== 'ENOENT')
                        reject(err);
                    else {
                        if (data) {
                            let parsedData = genericParser.parse(data) as any;
                            let accountData: userAccountData[] = [];
                            if (parsedData.users) {
                                for (let steamID64 in parsedData.users) {
                                    accountData.push({ steamID64: steamID64, accountID: steamID_64_ToAccountID(steamID64), name: parsedData.users[steamID64].AccountName });
                                }
                            }
                            resolve(accountData);
                        }
                        else
                            resolve([]);
                    }
                } catch (error) {
                    reject(error);
                }
            });
        }
        else {
            Glob('userdata/+([0-9])/', { silent: true, cwd: steamDirectory }, (err, files) => {
                if (err)
                    reject(err);
                else {
                    let getUserId = function (filename: string) {
                        return /userdata(\\|\/)(.*?)(\\|\/)/i.exec(filename)[2];
                    }

                    let accountData: userAccountData[] = [];
                    for (let i = 0; i < files.length; i++) {
                        let userId = getUserId(files[i]);
                        accountData.push({ steamID64: 'unavailable', accountID: userId, name: userId });
                    }
                    resolve(accountData);
                }
            });
        }
    });
开发者ID:kencinder,项目名称:steam-rom-manager,代码行数:44,代码来源:get-available-logins.ts


示例11: it

    it('appends multiple rules', async () => {
      const repo = await setupEmptyRepository()
      const path = repo.path

      await GitProcess.exec(
        ['config', '--local', 'core.autocrlf', 'true'],
        path
      )

      const ignoreFile = `${path}/.gitignore`
      await FSE.writeFile(ignoreFile, 'node_modules\n')

      await appendIgnoreRule(repo, ['yarn-error.log', '.eslintcache', 'dist/'])

      const gitignore = await FSE.readFile(ignoreFile)

      const expected = 'node_modules\nyarn-error.log\n.eslintcache\ndist/\n'
      expect(gitignore.toString('utf8')).equals(expected)
    })
开发者ID:ghmoore,项目名称:desktop,代码行数:19,代码来源:gitignore-test.ts


示例12: async

const getPost = async (postPath: string): Promise<any> => {
  const postDataPath: string = path.resolve(POSTS_DIR, postPath, "data.json");

  try {
    const postData: string = await fs.readFile(postDataPath, "utf-8");
    const post = JSON.parse(postData);

    return {
      ...post,
      abstract: converter.makeHtml(post.abstract),
      slug: postPath.split("-").splice(1).join("-"),
      path: postPath,
    };
  } catch (error) {
    console.error(error);
  }

  return null;
};
开发者ID:drublic,项目名称:vc,代码行数:19,代码来源:getPosts.ts


示例13: renderTemplateHtml

export function renderTemplateHtml(extensionPath: string, templateName: string, templateValues: object): Thenable<string> {
    let templatePath = path.join(extensionPath, 'resources', templateName);

    // 1) Read the template from the disk
    // 2) Compile it as a handlebars template and render the HTML
    // 3) On failure, return a simple string as an error
    return fs.readFile(templatePath, 'utf-8')
        .then(templateText => {
            let template = handlebars.compile(templateText);
            return template(templateValues);
        })
        .then(
            undefined,
            error => {
                logDebug(error);
                return LocalizedConstants.msgErrorLoadingTab;
            }
        );
}
开发者ID:AlexxNica,项目名称:sqlopsstudio,代码行数:19,代码来源:utils.ts


示例14: transformTravisConfig

export async function transformTravisConfig(
    inDir: string, outDir: string): Promise<void> {
  const inTravisPath = path.join(inDir, travisConfigFile);

  // If no `travis.yml` file exists, do nothing.
  if (!await fse.pathExists(inTravisPath)) {
    return;
  }

  const travisBlob = await fse.readFile(inTravisPath, 'utf-8');
  const travisConfig = safeLoad(travisBlob) as Partial<TravisConfig>| undefined;

  // It's possible for a `travis.yml` to be empty, or otherwise not an object.
  // If this happens, do nothing.
  if (!travisConfig) {
    return;
  }

  let beforeScripts = configToArray(travisConfig.before_script);
  let testScripts = configToArray(travisConfig.script);
  let installScripts = configToArray(travisConfig.install);

  // remove use of `bower` and `polymer install`
  beforeScripts = removeBowerAndPolymerInstall(beforeScripts);
  testScripts = removeBowerAndPolymerInstall(testScripts);
  installScripts = removeBowerAndPolymerInstall(installScripts);

  // remove TS and formatting checks
  beforeScripts = removeTypingsAndFormattingChecks(beforeScripts);

  // use `--npm` in `polymer test` and `wct` commands
  testScripts = addNPMFlag(testScripts);

  setConfig(travisConfig, 'before_script', beforeScripts);
  setConfig(travisConfig, 'script', testScripts);
  setConfig(travisConfig, 'install', installScripts);

  const outPath = path.join(outDir, travisConfigFile);
  const travisBlobOut =
      safeDump(travisConfig, {lineWidth: -1}).split('\n').join(EOL) + EOL;
  await fse.writeFile(outPath, travisBlobOut);
}
开发者ID:,项目名称:,代码行数:42,代码来源:


示例15: getDocs

export function getDocs(req: restify.Request, res: restify.Response, next: restify.Next) {
    let docType: string = req.params.docType;
    let url: string = req.params.url;
    console.log('getDocs: ' + JSON.stringify(req.params));
    if (!url) {
        url = 'index.html';
    }
    if (url === 'db.json' || url === 'index.html' || url === 'index.json') {
        fs.readFile(rootPath + docType + '/' + url, { encoding: 'utf-8' }, (err, data) => {
            if (err) {
                res.json(400, err);
            } else {
                res.writeHead(200, {
                    'Content-Type': url.endsWith('.html') ? 'application/json' : 'text/html',
                });
                res.write(data);
                res.end();
            }
        });
    } else {
        url = url.replace('.html', '');
        if (!docsLoadingState) {
            res.json(400, { message: 'docsDB not load ok' });
        } else {
            let isHasDos = (docType in docsDB);
            let result;
            if (isHasDos) {
                result = docsDB[docType][url];
            }
            if (result) {
                res.writeHead(200, {
                    'Content-Type': 'text/html',
                });
                res.write(result);
                res.end();
            } else {
                res.json(400, { message: 'not found' });
            }

        }
    }
}
开发者ID:snippetmodule,项目名称:docs-search-client,代码行数:42,代码来源:docs.ts


示例16: buildLambda

 () => {
   let zipFile = null;
   return fs
     .readFile(path.resolve(__dirname, './templates/lambda/zip/src.zip'))
     .then(contents => {
       zipFile = contents;
       return buildLambda({
         name: 'MyGreatFunction',
         options: {
           MemorySize: 256
         },
         output: true,
         parameters: ['Role'],
         path: path.resolve(__dirname, './examples/zip/')
       }).then(({ FunctionResource, Zip }) => {
         expect(Zip.size).toEqual(zipFile.size);
         expect(FunctionResource).toEqual({
           Name: 'MyGreatFunction',
           Properties: {
             Code: {
               S3Bucket: {
                 Ref: 'MyGreatFunctionS3BucketParam',
                 kind: 'Ref'
               },
               S3Key: { Ref: 'MyGreatFunctionS3KeyParam', kind: 'Ref' }
             },
             FunctionName: 'MyFunction',
             Handler: 'index.handler',
             MemorySize: 256,
             Role: {
               Ref: 'MyGreatFunctionRole',
               kind: 'Ref'
             },
             Runtime: 'nodejs6.10',
             Timeout: 30
           },
           Type: 'AWS::Lambda::Function',
           kind: 'Resource'
         });
       });
     });
 },
开发者ID:arminhammer,项目名称:wolkenkratzer,代码行数:42,代码来源:zip.spec.ts


示例17: Promise

    return new Promise((resolve: (val: string) => void) => {
      const filePath: string = this.getFilePath(key);

      fs.readFile(filePath, 'utf8', (err: string, fileValue: string) => {
        if (err) {
          return resolve(null);
        }

        const data: string[] = fileValue.toString().split('\n', 2);
        const meta: any = JSON.parse(data[0]);

        if (this.getCurrentTime() >= meta.expireTime) {
          del(filePath, {force: true})
            .then(() => {
              return resolve(null);
            });
        } else {
          resolve(data[1]);
        }
      });
    });
开发者ID:RapidFiring,项目名称:nodetests,代码行数:21,代码来源:file.ts


示例18: require

 () => {
   let zipFile = null;
   const testTemplate = require('./templates/lambda/zip/template.json');
   return fs
     .readFile(path.resolve(__dirname, './templates/lambda/zip/src.zip'))
     .then(contents => {
       zipFile = contents;
       return buildZipLambdaTemplate({
         name: 'MyGreatFunction',
         options: {
           MemorySize: 256
         },
         output: true,
         parameters: ['Role'],
         path: path.resolve(__dirname, './examples/zip/')
       }).then(({ Template, Zip }) => {
         expect(Zip.size).toEqual(zipFile.size);
         expect(Template.build()).toEqual(testTemplate);
       });
     });
 },
开发者ID:arminhammer,项目名称:wolkenkratzer,代码行数:21,代码来源:zip.spec.ts


示例19: enumerate_child_files_recursive

enumerate_child_files_recursive('source/', function (err, results) {
  if (err) throw err;
  for (let result of results) {
    var is_md = new RegExp(".md");
    if (is_md.test(result)) {
      fs.readFile(result, 'utf8', function (err, data) {
        if (err) {
          return console.log(err);
        }
        var backtick_positions = find(data, "```"); //find positions of backticks

        for (var i = 0, backtick_positions_1 = backtick_positions; i < backtick_positions_1.length; i++) {
          var backtick_position = backtick_positions_1[i];
          if (isEven(i)) {
            var tag = '{% raw %}';
          } else {
            var tag = '{% endraw %}';
            backtick_position += 3; //after backticks
          }
          data = data.splice(backtick_position, 0, tag);
          var newPos = [];
          for (let pos of backtick_positions_1) {
            pos += tag.length;
            newPos.push(pos);
          }
          backtick_positions_1 = newPos;
        }
        data = data.replace('{{site.baseurl}}', 'https://ns-docs.herokuapp.com');
        data = data.replace('`{{ }}`', '{%raw%}`{{ }}`{%endraw}');
        result = result.replace('start\\introduction', 'index');
        result = result.replace('start/introduction', 'index');
        console.log(result);
        fs.writeFile(result, data, (err) => {
          if (err) throw err;
          //console.log('Processed: ' + result);
        });
      });
    }
  }
});
开发者ID:georgeedwards,项目名称:docs,代码行数:40,代码来源:build.ts


示例20: function

const handler = function (req, res) {
    const url = parse(req.url);

    const parts = ['event-sender', 'amplitude', 'googleAnalytics'];

    if (parts.some(item => req.url.includes(item))) {
        stat(req, res, [__dirname, join(__dirname, 'node_modules/@waves')]);
        return null;
    }

    if (url.href.includes('/choose/')) {
        const [platform, connection, build] = url.href.replace('/choose/', '').split('/');
        const cookie = serialize('session', `${platform},${connection},${build}`, {
            maxAge: 60 * 60 * 24,
            path: '/'
        });

        res.setHeader('Set-Cookie', cookie);
        res.statusCode = 302;
        res.setHeader('Location', req.headers.referer);
        res.end();

        return null;
    }

    if (req.url.includes('/package.json')) {
        res.end(readFileSync(join(__dirname, 'package.json')));
        return null;
    }

    const parsed = parseCookie(req.headers.cookie);

    if (!parsed) {
        readFile(join(__dirname, 'chooseBuild.hbs'), 'utf8').then((file) => {
            res.end(compile(file)({ links: getBuildsLinks(req.headers['user-agent']) }));
        });
    } else {
        route(parsed.connection, parsed.build, parsed.platform)(req, res);
    }
};
开发者ID:wavesplatform,项目名称:WavesGUI,代码行数:40,代码来源:server.ts



注:本文中的fs-extra.readFile函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
TypeScript fs-extra.readFileSync函数代码示例发布时间:2022-05-25
下一篇:
TypeScript fs-extra.read函数代码示例发布时间:2022-05-25
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap