本文整理汇总了TypeScript中pify类的典型用法代码示例。如果您正苦于以下问题:TypeScript pify类的具体用法?TypeScript pify怎么用?TypeScript pify使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了pify类的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的TypeScript代码示例。
示例1: it
it('should post progress for uploads', async () => {
const scope =
nock(Utils.baseUrl)
.post(
'/upload/youtube/v3/videos?part=id%2Csnippet¬ifySubscribers=false&uploadType=multipart')
.reply(200);
const fileName = path.join(__dirname, '../../test/fixtures/mediabody.txt');
const fileSize = (await pify(fs.stat)(fileName)).size;
const google = new GoogleApis();
const youtube = google.youtube('v3');
const progressEvents = new Array<number>();
await youtube.videos.insert(
{
part: 'id,snippet',
notifySubscribers: false,
requestBody: {
snippet: {
title: 'Node.js YouTube Upload Test',
description:
'Testing YouTube upload via Google APIs Node.js Client'
}
},
media: {body: fs.createReadStream(fileName)}
},
{
onUploadProgress: (evt: {bytesRead: number}) => {
progressEvents.push(evt.bytesRead);
}
});
assert(progressEvents.length > 0);
assert.strictEqual(progressEvents[0], fileSize);
scope.done();
});
开发者ID:dmytrobanasko,项目名称:google-api-nodejs-client,代码行数:33,代码来源:test.media.ts
示例2: before
before(async () => {
const files = (await pify(glob)(__dirname + "/*.spec.ts")).map(async file => ({
name: file,
contents: (await fs.readFile(file)).toString()
}));
return (await Promise.all(files)).forEach(({ contents, name }) => {
const testNames = contents.match(/\/\/ it: [^\n]+\n/g);
const tests = contents.split(/\/\/ it: .+\n/).filter(line => line.length);
const suiteName = name.substring(name.lastIndexOf("/") + 1);
describe(suiteName, () => {
zip(testNames, tests).forEach(([name, value]) => {
if (name.includes(":skip")) {
return;
}
const testName = name.replace("// it:", "").trim();
it(testName, async () => {
const result = await evaluate(value);
return assert.isTrue(typeof result === "boolean" && result);
});
});
});
});
});
开发者ID:metaes,项目名称:metaes,代码行数:25,代码来源:runner.ts
示例3: main
async function main() {
if (args.length) {
args.forEach(async url => {
await gen.generateAPI(url);
console.log('Generated API for ' + url);
});
} else {
console.log('Removing old APIs...');
await pify(rimraf)(path.join(__dirname, '../../../src/apis'));
console.log('Generating APIs...');
await gen.generateAllAPIs();
console.log('Finished generating APIs!');
}
}
开发者ID:sgaluza,项目名称:google-api-nodejs-client,代码行数:14,代码来源:generate.ts
示例4: pify
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import * as cp from 'child_process';
import * as mv from 'mv';
import {ncp} from 'ncp';
import * as pify from 'pify';
import * as tmp from 'tmp';
const mvp = pify(mv);
const ncpp = pify(ncp);
const keep = !!process.env.GANC_KEEP_TEMPDIRS;
const stagingDir = tmp.dirSync({keep, unsafeCleanup: true});
const stagingPath = stagingDir.name;
const pkg = require('../../package.json');
const spawnp = (command: string, args: string[], options: cp.SpawnOptions = {}):
Promise<void> => {
return new Promise((resolve, reject) => {
cp.spawn(
command, args,
Object.assign(options, {stdio: 'inherit', shell: true}))
.on('close',
(code, signal) => {
if (code === 0) {
开发者ID:dmytrobanasko,项目名称:google-api-nodejs-client,代码行数:31,代码来源:test.kitchen.ts
示例5: doPublish
function doPublish(packageDir: string, gitRemoteUrl: string, params: Params): Promise<Result> {
const writeFile = pify(fs.writeFile),
gitRepoDir = path.join(params.tempDir, 'repo'),
packDir = path.join(params.tempDir, 'pack'),
commitTextPath = path.join(params.tempDir, 'commitMessage.txt'),
tagTextPath = path.join(params.tempDir, 'tagMessage.txt'),
cleanupOperations: Promise<any>[] = [];
// launch setup operations
const initialCleanDone = rimraf(params.tempDir, { glob: false });
const directoryReady = initialCleanDone.then(() => mkdirp(packDir));
const commitTextWritten = Promise.all([params.commitTextOp, directoryReady])
.then(([commitText]) => writeFile(commitTextPath, commitText));
const tagTextWritten = Promise.all([params.tagMessageTextOp, directoryReady])
.then(([tagMessageText]) => writeFile(tagTextPath, tagMessageText));
// simultaneously ask NPM to pack up the package dir and create a clone of the remote URL
const tarballCreated = packPackageIntoTarball();
const doneCloning = cloneRemoteToTempRepo();
return replaceRepoWithPackContents()
.then(stageAllRepoChanges)
.then(() => params.prepublishCallback(gitRepoDir))
.then(shouldContinue =>
shouldContinue ? finishReleaseAndReturnResult() : cleanUpAndReturnChanged(publish.CANCELLED));
function finishReleaseAndReturnResult() {
return stageAllRepoChanges()
.then(queryRepoStatus)
.then(hasChanges => hasChanges ? commitChanges() : Promise.resolve())
.then(tagLastCommit)
.then(pushDefaultBranch)
.then(() => cleanUpAndReturnChanged(publish.PUSHED));
}
function cleanUpAndReturnChanged(conclusion: publish.Conclusions) {
cleanupOperations.push(rimraf(params.tempDir, { glob: false }));
return Promise.all(cleanupOperations).then(() => ({ conclusion: conclusion }));
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// LOCAL HELPER FUNCTIONS
function packPackageIntoTarball() {
return directoryReady
.then(() => exec(`npm pack "${packageDir}"`, { cwd: packDir }))
.then(() => {
// pack succeeded! Schedule a cleanup and return the full path
cleanupOperations.push(exec(`npm cache clean ${params.originalPackageInfo.name}@${params.originalPackageInfo.version}`));
return path.join(packDir, computeTarballName());
});
}
function computeTarballName() {
let name = params.originalPackageInfo.name;
if (name[0] === '@') {
// in generating tarball names, npm special-cases scoped packages.
name = name.substr(1).replace(/\//g, '-');
}
return `${name}-${params.originalPackageInfo.version}.tgz`;
}
function cloneRemoteToTempRepo() {
return initialCleanDone.then(() => {
execSync(`git clone --quiet --depth 1 ${gitRemoteUrl} "${gitRepoDir}"`, { stdio: 'inherit' });
});
}
function replaceRepoWithPackContents() {
// in order to allow for the new release to overwrite the old one (including possibly removing/renaming files),
// we remove everything that was in the repo before. To do this, use an exclusionary glob.
const cleanPattern = path.join(gitRepoDir, '!(.git)');
// tell glob to treat the leading '.' in filename (e.g. Linux/Mac hidden files) as a normal character.
// this is necessary so that we can successfully delete files that begin with '.'
const cleanOptions = { glob: { dot: true } };
const doneCleaning = doneCloning.then(() => rimraf(cleanPattern, cleanOptions));
return Promise.all<any>([tarballCreated, doneCleaning])
.then(([tarballPath] : [string]) => unpack(tarballPath, gitRepoDir));
}
function stageAllRepoChanges() {
return exec(`git add --all`, { cwd: gitRepoDir });
}
function queryRepoStatus() {
return exec(`git status --porcelain`, { cwd: gitRepoDir })
.then((statusOutput) => {
return statusOutput.trim().length !== 0;
});
}
function commitChanges() {
const commitCommandText = `git commit --file="${commitTextPath}" --allow-empty-message --no-verify`;
return commitTextWritten.then(() => exec(commitCommandText, { cwd: gitRepoDir }));
}
function tagLastCommit() {
return Promise.all([params.mainTagNameOp, tagTextWritten])
//.........这里部分代码省略.........
开发者ID:theoy,项目名称:npm-git-publish,代码行数:101,代码来源:publish.ts
示例6: pify
import test from 'ava';
import * as pem from 'pem';
import * as pify from 'pify';
import * as got from 'got';
import {createServer, createSSLServer} from './helpers/server';
let http;
let https;
const pemP = pify(pem, Promise);
test.before('setup', async () => {
const caKeys = await pemP.createCertificate({days: 1, selfSigned: true});
const caRootKey = caKeys.serviceKey;
const caRootCert = caKeys.certificate;
const keys = await pemP.createCertificate({
serviceCertificate: caRootCert,
serviceKey: caRootKey,
serial: Date.now(),
days: 500,
country: '',
state: '',
locality: '',
organization: '',
organizationUnit: '',
commonName: 'sindresorhus.com'
});
const key = keys.clientKey;
开发者ID:cyounkins,项目名称:typed-got,代码行数:31,代码来源:redirects.ts
示例7: IsUri
export function IsUri(uri: string): boolean {
return /^([a-z0-9+.-]+):(?:\/\/(?:((?:[a-z0-9-._~!$&'()*+,;=:]|%[0-9A-F]{2})*)@)?((?:[a-z0-9-._~!$&'()*+,;=]|%[0-9A-F]{2})*)(?::(\d*))?(\/(?:[a-z0-9-._~!$&'()*+,;=:@/]|%[0-9A-F]{2})*)?|(\/?(?:[a-z0-9-._~!$&'()*+,;=:@]|%[0-9A-F]{2})+(?:[a-z0-9-._~!$&'()*+,;=:@/]|%[0-9A-F]{2})*)?)(?:\?((?:[a-z0-9-._~!$&'()*+,;=:/?@]|%[0-9A-F]{2})*))?(?:#((?:[a-z0-9-._~!$&'()*+,;=:/?@]|%[0-9A-F]{2})*))?$/i.test(uri);
}
/***********************
* Data aquisition
***********************/
import * as promisify from "pify";
import { Readable } from "stream";
import { parse } from "url";
import { sep } from "path";
const stripBom: (text: string) => string = require("strip-bom");
const getUri = require("get-uri");
const getUriAsync: (uri: string, options: { headers: { [key: string]: string } }) => Promise<Readable> = promisify(getUri);
/**
* Loads a UTF8 string from given URI.
*/
export async function ReadUri(uri: string, headers: { [key: string]: string } = {}): Promise<string> {
try {
const readable = await getUriAsync(uri, { headers: headers });
const readAll = new Promise<string>(function (resolve, reject) {
let result = "";
readable.on("data", data => result += data.toString());
readable.on("end", () => resolve(result));
readable.on("error", err => reject(err));
});
开发者ID:indrajithbandara,项目名称:autorest,代码行数:29,代码来源:uri.ts
示例8: pify
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import * as assert from 'assert';
import * as fs from 'fs';
import * as nock from 'nock';
import * as path from 'path';
import * as pify from 'pify';
import {Utils} from './../utils';
const fsp = pify(fs);
nock.disableNetConnect();
const samples = {
jwt: require('../../../samples/jwt')
};
describe('Auth samples', () => {
afterEach(() => {
nock.cleanAll();
});
it('should support JWT', async () => {
const scope = nock(Utils.baseUrl)
.get('/drive/v2/files')
开发者ID:dmytrobanasko,项目名称:google-api-nodejs-client,代码行数:31,代码来源:test.samples.auth.ts
示例9: assert
import * as pify from 'pify';
function assert(actual: string, expected: string): void {
if (actual !== expected) {
throw new Error(`${JSON.stringify(actual)} !== ${JSON.stringify(expected)}`);
}
}
const fs = {
readFile: (file: string, callback: Function) => {
let result: any = undefined;
if (file === 'foo.txt') {
result = 'foo';
} else if (file === 'bar.txt') {
result = 'bar';
}
callback(undefined, result);
}
};
const fsP = pify(fs);
fsP.readFile('foo.txt').then((result: string) => assert(result, 'foo'));
pify(fs.readFile)('foo.txt').then((result: string) => assert(result, 'foo'));
pify(fs.readFile, Promise)('bar.txt').then((result: string) => assert(result, 'bar'));
开发者ID:Crevil,项目名称:DefinitelyTyped,代码行数:27,代码来源:pify-tests.ts
示例10: require
return /^([a-z0-9+.-]+):(?:\/\/(?:((?:[a-z0-9-._~!$&'()*+,;=:]|%[0-9A-F]{2})*)@)?((?:[a-z0-9-._~!$&'()*+,;=]|%[0-9A-F]{2})*)(?::(\d*))?(\/(?:[a-z0-9-._~!$&'()*+,;=:@/]|%[0-9A-F]{2})*)?|(\/?(?:[a-z0-9-._~!$&'()*+,;=:@]|%[0-9A-F]{2})+(?:[a-z0-9-._~!$&'()*+,;=:@/]|%[0-9A-F]{2})*)?)(?:\?((?:[a-z0-9-._~!$&'()*+,;=:/?@]|%[0-9A-F]{2})*))?(?:#((?:[a-z0-9-._~!$&'()*+,;=:/?@]|%[0-9A-F]{2})*))?$/i.test(uri);
}
/***********************
* Data aquisition
***********************/
import * as promisify from "pify";
import { Readable } from "stream";
import { parse } from "url";
import { sep } from "path";
// polyfills for language support
require("../polyfill.min.js");
const stripBom: (text: string) => string = require("strip-bom");
const getUri = require("get-uri");
const getUriAsync: (uri: string) => Promise<Readable> = promisify(getUri);
/**
* Loads a UTF8 string from given URI.
*/
export async function ReadUri(uri: string): Promise<string> {
try {
const readable = await getUriAsync(uri);
const readAll = new Promise<string>(function (resolve, reject) {
let result = "";
readable.on("data", data => result += data.toString());
readable.on("end", () => resolve(result));
readable.on("error", err => reject(err));
});
开发者ID:lmazuel,项目名称:autorest,代码行数:30,代码来源:uri.ts
注:本文中的pify类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论