本文整理汇总了TypeScript中fs-extra-promise.existsAsync函数的典型用法代码示例。如果您正苦于以下问题:TypeScript existsAsync函数的具体用法?TypeScript existsAsync怎么用?TypeScript existsAsync使用的例子?那么, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了existsAsync函数的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的TypeScript代码示例。
示例1: generate
async function generate(rootDir: string) {
const pbconfigPath = path.join(rootDir, 'pbconfig.json');
if (!(await fs.existsAsync(pbconfigPath))) {
if (await fs.existsAsync(path.join(rootDir, 'protobuf'))) {
const pbconfigPath = path.join(rootDir, 'protobuf', 'pbconfig.json')
if (!await (fs.existsAsync(pbconfigPath))) {
await fs.writeFileAsync(pbconfigPath, pbconfigContent, 'utf-8');
}
await generate(path.join(rootDir, 'protobuf'));
}
else {
throw '请首先执行 pb-egret add 命令'
}
return;
}
const pbconfig: ProtobufConfig = await fs.readJSONAsync(path.join(rootDir, 'pbconfig.json'));
const tempfile = path.join(os.tmpdir(), 'pbegret', 'temp.js');
await fs.mkdirpAsync(path.dirname(tempfile));
const output = path.join(rootDir, pbconfig.outputFile);
const dirname = path.dirname(output);
await fs.mkdirpAsync(dirname);
const protoRoot = path.join(rootDir, pbconfig.sourceRoot);
const fileList = await fs.readdirAsync(protoRoot);
const protoList = fileList.filter(item => path.extname(item) === '.proto')
if (protoList.length == 0) {
throw ' protofile 文件夹中不存在 .proto 文件'
}
await Promise.all(protoList.map(async (protofile) => {
const content = await fs.readFileAsync(path.join(protoRoot, protofile), 'utf-8')
if (content.indexOf('package') == -1) {
throw `${protofile} 中必须包含 package 字段`
}
}))
const args = ['-t', 'static', '-p', protoRoot, protoList.join(" "), '-o', tempfile]
if (pbconfig.options['no-create']) {
args.unshift('--no-create');
}
if (pbconfig.options['no-verify']) {
args.unshift('--no-verify');
}
await shell('pbjs', args);
let pbjsResult = await fs.readFileAsync(tempfile, 'utf-8');
pbjsResult = 'var $protobuf = window.protobuf;\n$protobuf.roots.default=window;\n' + pbjsResult;
await fs.writeFileAsync(output, pbjsResult, 'utf-8');
const minjs = UglifyJS.minify(pbjsResult);
await fs.writeFileAsync(output.replace('.js', '.min.js'), minjs.code, 'utf-8');
await shell('pbts', ['--main', output, '-o', tempfile]);
let pbtsResult = await fs.readFileAsync(tempfile, 'utf-8');
pbtsResult = pbtsResult.replace(/\$protobuf/gi, "protobuf").replace(/export namespace/gi, 'declare namespace');
pbtsResult = 'type Long = protobuf.Long;\n' + pbtsResult;
await fs.writeFileAsync(output.replace(".js", ".d.ts"), pbtsResult, 'utf-8');
await fs.removeAsync(tempfile);
}
示例2: lint
export default async function lint() {
// typescript
const typescriptFileFailures = await lintAsync();
if (typescriptFileFailures.length) {
// log all failures with some basic formatting
error('');
for (const fileFailure of typescriptFileFailures) {
error(`Found ${yellow(fileFailure.failureCount.toString())} failure(s) in ${yellow(fileFailure.failures[0].getFileName())}:`);
for (const failure of fileFailure.failures) {
const fileName = failure.getFileName();
if (!sourceFileLines[fileName]) {
// attention: sourceFile is a private property!
sourceFileLines[fileName] = (failure as any).sourceFile.text.split('\n');
}
const lines = sourceFileLines[fileName];
const { line, character } = failure.getStartPosition().getLineAndCharacter();
error(` ${failure.getFailure()} ${grey(`(at [${line + 1}:${character + 1}]: ${lines[line].trim()})`)}`);
}
error('');
}
}
// documentation
const documentationFailures = [];
if (!project.private) {
if (!(await existsAsync(join(process.cwd(), 'README.md')))) {
documentationFailures.push(`You have ${yellow('no README.md')}.`);
}
if (!project.keywords || !project.keywords.length) {
documentationFailures.push(`You have ${yellow('no keywords')} set in your ${yellow('package.json')}.`);
}
if (!(await existsAsync(join(process.cwd(), 'examples')))) {
documentationFailures.push(`You have ${yellow('no examples/')} directory.`);
} else {
const contents = (await readdirAsync(join(process.cwd(), 'examples'))).filter(content => content !== '.DS_Store');
if (!contents.length) {
documentationFailures.push(`Your ${yellow('examples/')} directory ${yellow('is empty')}.`);
}
}
}
if (documentationFailures.length) {
error('');
error(`You're project ${yellow(`isn't private`)}, but it has ${yellow(documentationFailures.length.toString())} documentation failure(s).`);
documentationFailures.forEach(msg => error(` ${msg}`));
error('');
}
if (typescriptFileFailures.length || documentationFailures.length) {
throw `${cyan('lint')} failed.`;
}
};
示例3: add
async function add(egretProjectRoot: string) {
console.log('正在将 protobuf 源码拷贝至项目中...');
await fs.copyAsync(path.join(root, 'dist'), path.join(egretProjectRoot, 'protobuf/library'));
await fs.mkdirpSync(path.join(egretProjectRoot, 'protobuf/protofile'));
await fs.mkdirpSync(path.join(egretProjectRoot, 'protobuf/bundles'));
await fs.writeFileAsync((path.join(egretProjectRoot, 'protobuf/pbconfig.json')), pbconfigContent, 'utf-8');
const egretPropertiesPath = path.join(egretProjectRoot, 'egretProperties.json');
if (await fs.existsAsync(egretPropertiesPath)) {
console.log('正在将 protobuf 添加到 egretProperties.json 中...');
const egretProperties = await fs.readJSONAsync(egretPropertiesPath);
egretProperties.modules.push({ name: 'protobuf-library', path: 'protobuf/library' });
egretProperties.modules.push({ name: 'protobuf-bundles', path: 'protobuf/bundles' });
await fs.writeFileAsync(path.join(egretProjectRoot, 'egretProperties.json'), JSON.stringify(egretProperties, null, '\t\t'));
console.log('正在将 protobuf 添加到 tsconfig.json 中...');
const tsconfig = await fs.readJSONAsync(path.join(egretProjectRoot, 'tsconfig.json'));
tsconfig.include.push('protobuf/**/*.d.ts');
await fs.writeFileAsync(path.join(egretProjectRoot, 'tsconfig.json'), JSON.stringify(tsconfig, null, '\t\t'));
}
else {
console.log('输入的文件夹不是白鹭引擎项目')
}
}
示例4: resolve
return new Promise<Operations>((resolve, reject) => {
return fs.existsAsync(launchJsonPath).then(exists => {
if (exists) {
resolve(operations);
}
else {
operations.addLaunchJson = true;
resolve(operations);
}
});
});
示例5: generateTypings
export async function generateTypings(
declarationDir: string,
filePatterns = sourceFilePatterns
) {
if (project.typings) {
debug('Generate typings.');
const filePaths = await globby(filePatterns);
const options = {
declaration: true,
declarationDir
};
const result = createProgram(filePaths, options).emit(
undefined, // targetSourceFile
undefined, // writeFile
undefined, // cancellationToken
true // emitOnlyDtsFiles
);
if (result.diagnostics.length) {
const message = result.diagnostics
.map(({ messageText, file, start }) => {
if (file && start) {
const pos = file.getLineAndCharacterOfPosition(start);
const frame = codeFrame(
file.getFullText(),
pos.line + 1,
pos.character + 1,
{
highlightCode: true
}
);
return `${messageText}\n${frame}`;
} else {
return messageText;
}
})
.join('\n');
throw `\n${message}\n`;
}
// check if they exist at the same place where it is configured in your package.json
const exist = await existsAsync(join(process.cwd(), project.typings));
if (!exist) {
throw `${red('typings')} do not exist in ${project.typings}`;
}
}
}
示例6: unit
export default async function unit(options) {
const unitEntry = `./${project.ws.testsDir}/unit.${project.ws.entryExtension}`;
const hasUnitTests = await existsAsync(unitEntry);
if (!hasUnitTests) {
warn(`${yellow('warn!')} You tried to run unit tests, but ${yellow(unitEntry)} doesn't exist.`);
return;
}
await removeAsync(project.ws.distTestsDir);
let exitCode;
switch (project.ws.type) {
case TYPE.NODE:
await compileAsync(nodeUnitOptions);
const files = [
path.join(nodeUnitOptions.output.path, nodeUnitOptions.output.filename)
];
exitCode = await mochaTestAsync(files);
break;
case TYPE.SPA:
if (project.ws.i18n) {
await compileAsync(createLocaleSpecificOptions(spaUnitOptions, project.ws.i18n.locales[0]));
} else {
await compileAsync(spaUnitOptions);
}
exitCode = await karmaTestAsync(options);
break;
case TYPE.BROWSER:
if (project.ws.i18n) {
await compileAsync(createLocaleSpecificOptions(browserUnitOptions, project.ws.i18n.locales[0]));
} else {
await compileAsync(browserUnitOptions);
}
exitCode = await karmaTestAsync(options);
break;
}
if (exitCode !== 0) {
throw `${cyan('unit')} failed.`;
}
};
示例7:
.then(() => {
return fs.existsAsync(fooTablePath)
.then((result) => assert.equal(true, result))
})
示例8: init
async function init(options: any) {
debug(`Init E2E tests.`);
// build
const e2eEntry = `./${project.ws.testsDir}/e2e.${project.ws.entryExtension}`;
const hasE2eTests = await existsAsync(e2eEntry);
if (!hasE2eTests) {
warn(
`${yellow('warn!')} You tried to run e2e tests, but ${yellow(
e2eEntry
)} doesn't exist.`
);
return;
}
await removeAsync(project.ws.distTestsDir);
await compileAsync(getSpaE2eConfig(), 'e2e');
debug(`Build E2E tests.`);
// prepare selenium
let seleniumProcess: any;
let sauceConnectProcess: any;
let browsers: Array<any>;
if (options.grid) {
// at this place we know selenium config is set, no need for null checks
const selenium = project.ws.selenium as SeleniumGridConfig;
const { host, port, user, password } = selenium;
options.seleniumUrl = `http://${user ? `${user}:${password}@` : ''}${
host
}:${port}/wd/hub`;
browsers = options.browsers
? options.browsers.split(',').map(parseBrowser)
: await getBrowsers();
if (isSauceLabsHost(host)) {
sauceConnectProcess = await launchSauceConnect(selenium);
}
} else {
options.seleniumUrl = `http://localhost:4444/wd/hub`;
seleniumProcess = await runSeleniumServer();
const defaultBrowsers = 'ff'; // 'chrome,ff'
browsers = (options.browsers || defaultBrowsers)
.split(',')
.map(parseBrowser);
}
debug(`Configured selenium.`);
// spawn tests
// TODO: For now run everything in parallel. We could check `options.sequentially` to run it sequentially in the future.
await Promise.all(browsers.map(browser => spawnE2e(options, browser)));
// ran locally?
if (seleniumProcess) {
debug(`Tries to kill Selenium Process.`);
seleniumProcess.kill();
}
// ran with sauce connect?
if (sauceConnectProcess) {
debug(`Tries to close Sauce Connect.`);
sauceConnectProcess.close(() => debug(`Closed Sauce Connect.`));
}
}
示例9: lint
export default async function lint() {
// tslint
const tsintResult = await tslintAsync();
if (tsintResult.errorsCount) {
error('');
error(tsintResult.errors);
error('');
}
// eslint
const eslintResult = await eslintAsync();
if (eslintResult.errorsCount) {
error('');
error(eslintResult.errors.join('\n'));
error('');
}
// prettier
const formattedFiles = await formatAsync();
// documentation
const docsErrors: Array<string> = [];
if (!project.private) {
if (!await existsAsync(join(process.cwd(), 'README.md'))) {
docsErrors.push(`You have ${yellow('no README.md')}.`);
}
if (!project.keywords || !project.keywords.length) {
docsErrors.push(
`You have ${yellow('no keywords')} set in your ${yellow(
'package.json'
)}.`
);
}
if (!project.description) {
docsErrors.push(
`You have ${yellow('no description')} set in your ${yellow(
'package.json'
)}.`
);
}
}
if (docsErrors.length) {
error('');
error(
`You're project ${yellow(
`isn't private`
)}, but it has the following ${errors(docsErrors.length)}.`
);
docsErrors.forEach(msg => error(` ${msg}`));
error('');
}
// result
// all file paths here are absolute
const fixedFiles = uniq([
...tsintResult.fixedFiles,
...eslintResult.fixedFiles,
...formattedFiles
]);
if (fixedFiles.length) {
const count = cyan(fixedFiles.length.toString());
info(`automatically fixed ${count} ${files(fixedFiles.length)} ${smile}`);
debug(`list of fixed files: ${fixedFiles.join(', ')}`);
}
const totalErrors =
tsintResult.errorsCount + docsErrors.length + eslintResult.errorsCount;
if (totalErrors) {
const count = red(totalErrors.toString());
error(`found ${count} ${errors(totalErrors)}`);
error('');
throw `${cyan('lint')} failed.`;
}
}