本文整理匯總了TypeScript中fs-extra.readFile函數的典型用法代碼示例。如果您正苦於以下問題:TypeScript readFile函數的具體用法?TypeScript readFile怎麽用?TypeScript readFile使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。
在下文中一共展示了readFile函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的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);
});
示例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');
});
示例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);
}
示例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');
}
});
};
示例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/')
})
示例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('')
})
})
示例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
}
示例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));
});
}
示例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>
`;
}
示例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);
}
});
}
});
示例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)
})
示例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;
};
示例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;
}
);
}
示例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);
}
示例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' });
}
}
}
}