本文整理汇总了TypeScript中http.ClientRequest.on方法的典型用法代码示例。如果您正苦于以下问题:TypeScript ClientRequest.on方法的具体用法?TypeScript ClientRequest.on怎么用?TypeScript ClientRequest.on使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类http.ClientRequest
的用法示例。
在下文中一共展示了ClientRequest.on方法的7个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的TypeScript代码示例。
示例1: resolve
return new Promise<void>((resolve, reject) => {
let parsedUrl: url.Url = url.parse(urlString);
let request: ClientRequest = https.request({
host: parsedUrl.host,
path: parsedUrl.path,
agent: util.GetHttpsProxyAgent(),
rejectUnauthorized: vscode.workspace.getConfiguration().get("http.proxyStrictSSL", true)
}, (response) => {
if (response.statusCode == 301 || response.statusCode == 302) {
let redirectUrl: string | string[];
if (typeof response.headers.location === "string") {
redirectUrl = response.headers.location;
} else {
redirectUrl = response.headers.location[0];
}
return resolve(downloadCpptoolsJson(redirectUrl)); // Redirect - download from new location
}
if (response.statusCode != 200) {
return reject();
}
let downloadedBytes = 0; // tslint:disable-line
let cppToolsJsonFile: fs.WriteStream = fs.createWriteStream(util.getExtensionFilePath("cpptools.json"));
response.on('data', (data) => { downloadedBytes += data.length; });
response.on('end', () => { cppToolsJsonFile.close(); });
cppToolsJsonFile.on('close', () => { resolve(); });
response.on('error', (error) => { reject(); });
response.pipe(cppToolsJsonFile, { end: false });
});
request.on('error', (error) => { reject(); });
request.end();
});
示例2: getHttpsProxyAgent
return new Promise<string>((resolve, reject) => {
let parsedUrl: url.Url = url.parse(urlStr);
let request: ClientRequest = https.request({
host: parsedUrl.host,
path: parsedUrl.path,
agent: getHttpsProxyAgent(),
rejectUnauthorized: vscode.workspace.getConfiguration().get('http.proxyStrictSSL', true),
headers: headers
}, (response) => {
if (response.statusCode === 301 || response.statusCode === 302) { // If redirected
// Download from new location
let redirectUrl: string;
if (typeof response.headers.location === 'string') {
redirectUrl = response.headers.location;
} else {
redirectUrl = response.headers.location[0];
}
return resolve(downloadFileToStr(redirectUrl, headers));
}
if (response.statusCode !== 200) { // If request is not successful
return reject();
}
let downloadedData: string = '';
response.on('data', (data) => { downloadedData += data; });
response.on('error', (error) => { reject(error); });
response.on('end', () => { resolve(downloadedData); });
});
request.on('error', (error) => { reject(error); });
request.end();
});
示例3: addTimeOutHandler
export function addTimeOutHandler(request: ClientRequest, callback: (error: Error) => void) {
request.on("socket", function (socket: Socket) {
socket.setTimeout(60 * 1000, () => {
callback(new Error("Request timed out"))
request.abort()
})
})
}
示例4: extractChannelTitle
channels.forEach((channel: IChannel) => {
let liveUrl: string = channel.url.replace(/^http:\/\//, 'http://live.');
let request: ClientRequest = http.get(liveUrl, (res: IncomingMessage) => {
let url: string = channel.url;
let body: string = "";
res.setEncoding("utf8");
res.on("data", (chunk: string) => {
body += chunk;
});
res.on("error", (error: any) => {
console.log(`Conection Error : ${error.message}`);
});
res.on("end", () => {
let title: string = extractChannelTitle(body);
let broadcasting: boolean = checkBroadcasting(body);
if (broadcasting) {
if (lastChannelBroadcastings[url] === undefined ||
lastChannelBroadcastings[url] === false) {
lastChannelBroadcastings[url] = true;
notifier.notify({
title: title,
message: url,
icon: __dirname + "/../browser/notification.png",
sound: true,
wait: true,
});
notifier.on("click", (notifierObject: NodeNotifier, options: Notification) => {
electron.shell.openExternal(options.message + '/live');
});
}
} else {
lastChannelBroadcastings[url] = false;
}
updateTrayIcon();
if (mainWindow !== undefined) {
mainWindow.webContents.send("updateChannelStatus", JSON.stringify({
url: url,
title: title,
broadcasting: broadcasting,
}));
}
});
});
request.on("error", (error: any) => {
console.log(`Conection Error : ${error.message}`);
});
});
示例5: runPostRequest
function runPostRequest(host:string, path:string, body:string, callback:(ClientResponse)=>void) {
const options = {
hostname: host,
port: 3000,
path: path,
method: 'POST',
headers: {
'Content-Type': 'text/plain',
'Content-Length': Buffer.byteLength(body)
}
};
let request:ClientRequest = http.request(options, callback);
request.on('error', traceErrorIfPresent);
var splittedBody:Array<string> = body.split('');
while (splittedBody.length > 0) {
request.write(splittedBody.splice(0, 15).join(''));
}
request.end();
}
示例6:
req.removeHeader('Date');
// write
const chunk = Buffer.alloc(16390, 'Đ');
req.write(chunk);
req.write('a');
req.end();
// abort
req.abort();
// connection
req.connection.on('pause', () => { });
// event
req.on('data', () => { });
}
{
// Status codes
let codeMessage: string = http.STATUS_CODES['400']!;
codeMessage = http.STATUS_CODES[400]!;
}
{
let agent: http.Agent = new http.Agent({
keepAlive: true,
keepAliveMsecs: 10000,
maxSockets: Infinity,
maxFreeSockets: 256,
timeout: 15000
示例7: default
export default (request: ClientRequest, delays: Delays, options: any) => {
/* istanbul ignore next: this makes sure timed-out isn't called twice */
if (Reflect.has(request, reentry)) {
return noop;
}
(request as any)[reentry] = true;
let stopNewTimeouts = false;
const addTimeout = (delay: number, callback: (...args: any) => void, ...args: any): (() => void) => {
// An error had been thrown before. Going further would result in uncaught errors.
// See https://github.com/sindresorhus/got/issues/631#issuecomment-435675051
if (stopNewTimeouts) {
return noop;
}
// Event loop order is timers, poll, immediates.
// The timed event may emit during the current tick poll phase, so
// defer calling the handler until the poll phase completes.
let immediate: NodeJS.Immediate;
const timeout: NodeJS.Timeout = setTimeout(() => {
immediate = setImmediate(callback, delay, ...args);
/* istanbul ignore next: added in node v9.7.0 */
if (immediate.unref) {
immediate.unref();
}
}, delay);
/* istanbul ignore next: in order to support electron renderer */
if (timeout.unref) {
timeout.unref();
}
const cancel = (): void => {
clearTimeout(timeout);
clearImmediate(immediate);
};
cancelers.push(cancel);
return cancel;
};
const {host, hostname} = options;
const timeoutHandler = (delay: number, event: string): void => {
request.emit('error', new TimeoutError(delay, event));
request.abort();
};
const cancelers: Array<() => void> = [];
const cancelTimeouts = (): void => {
stopNewTimeouts = true;
cancelers.forEach(cancelTimeout => cancelTimeout());
};
request.on('error', (error: Error): void => {
if (error.message !== 'socket hang up') {
cancelTimeouts();
}
});
request.once('response', response => {
response.once('end', cancelTimeouts);
});
if (delays.request !== undefined) {
addTimeout(delays.request, timeoutHandler, 'request');
}
if (delays.socket !== undefined) {
const socketTimeoutHandler = (): void => {
timeoutHandler(delays.socket!, 'socket');
};
request.setTimeout(delays.socket, socketTimeoutHandler);
// `request.setTimeout(0)` causes a memory leak.
// We can just remove the listener and forget about the timer - it's unreffed.
// See https://github.com/sindresorhus/got/issues/690
cancelers.push((): void => {
request.removeListener('timeout', socketTimeoutHandler);
});
}
request.once('socket', (socket: net.Socket): void => {
const {socketPath} = request as any;
/* istanbul ignore next: hard to test */
if (socket.connecting) {
if (delays.lookup !== undefined && !socketPath && !net.isIP(hostname || host)) {
const cancelTimeout = addTimeout(delays.lookup, timeoutHandler, 'lookup');
socket.once('lookup', cancelTimeout);
}
if (delays.connect !== undefined) {
const timeConnect = () => addTimeout(delays.connect!, timeoutHandler, 'connect');
if (socketPath || net.isIP(hostname || host)) {
socket.once('connect', timeConnect());
} else {
//.........这里部分代码省略.........