当前位置: 首页>>代码示例>>TypeScript>>正文


TypeScript zlib.createGzip函数代码示例

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


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

示例1: stream_readable_pipe_test

////////////////////////////////////////////////////
/// Stream tests : http://nodejs.org/api/stream.html
////////////////////////////////////////////////////

// http://nodejs.org/api/stream.html#stream_readable_pipe_destination_options
function stream_readable_pipe_test() {
    var r = fs.createReadStream('file.txt');
    var z = zlib.createGzip();
    var w = fs.createWriteStream('file.txt.gz');
    r.pipe(z).pipe(w);
    r.close();
}
开发者ID:Crevil,项目名称:DefinitelyTyped,代码行数:12,代码来源:node-tests.ts

示例2: accepts

export function httpRespond<E>({req, res, type, value}: HttpParams<E>, callback?: ErrCallback) {
	assert.instanceOf(type, AbstractType)
	if (callback === undefined) callback = _ => {}
	assert.instanceOf(callback, Function)
	assert.instanceOf(req, http.IncomingMessage)
	assert.instanceOf(res, http.OutgoingMessage)
	try {
		res.setHeader('Content-Type', 'application/octet-stream')
		res.setHeader('sig', type.getSignature())
		const acceptsGzip = accepts(req).encoding(['gzip'])
		let outStream: Writable
		if (acceptsGzip) {
			res.setHeader('Content-Encoding', 'gzip')
			outStream = zlib.createGzip() //pipe into a zip stream to decrease size of response
		}
		else outStream = res
		function writeEndCallback(err: Error | null) {
			if (err) callback!(err)
			else if (!acceptsGzip) callback!(null)
		}
		if (req.headers.sig && req.headers.sig === type.getSignature()) { //if client already has type, only value needs to be sent
			writeValue({type, value, outStream}, writeEndCallback)
		}
		else writeTypeAndValue({type, value, outStream}, writeEndCallback) //otherwise, type and value need to be sent
		if (acceptsGzip) { //don't pipe until writing begins
			outStream.pipe(res)
				.on('finish', () => callback!(null))
		}
	}
	catch (err) { callback(err) }
}
开发者ID:calebsander,项目名称:structure-bytes,代码行数:31,代码来源:io.ts

示例3: function

    fs.exists(pathname, function (exist: any) {
        if (!exist) {
            // if the file is not found, return 404
            response.statusCode = 404;
            response.end(`File ${pathname} not found!`);
            return;
        }
        
        // if is a directory, then look for index.html
        if (fs.statSync(pathname).isDirectory()) {
            pathname += 'www/index.browser.html';
        }

        const ext = path.parse(pathname).ext;
        response.setHeader('Content-type', mimeType[ext] || 'text/plain');

        var raw = fs.createReadStream(pathname);
        var acceptEncoding = request.headers['accept-encoding'];
        if (!acceptEncoding) {
            acceptEncoding = '';
        }


        // Note: this is not a conformant accept-encoding parser.
        // See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.3

        // if (acceptEncoding.match(/\bdeflate\b/)) {
        //     response.writeHead(200, { 'Content-Encoding': 'deflate' });
        //     raw.pipe(zlib.createDeflate()).pipe(response);
        // } else 

        if (acceptEncoding.match(/\bgzip\b/)) {
            response.writeHead(200, { 'Content-Encoding': 'gzip' });
            raw.pipe(zlib.createGzip()).pipe(response);
        } else {
            response.writeHead(200, {});
            raw.pipe(response);
        }

        // read file from file system
        // Because all javascripts are loaded by the module loader, we don't directly read files from filesystem.
        // fs.readFile(pathname, function (err: any, data: any) {
        //     if (err) {
        //         res.statusCode = 500;
        //         res.end(`Error getting the file: ${err}.`);
        //     } else {
        //         // based on the URL path, extract the file extention. e.g. .js, .doc, ...
        //         const ext = path.parse(pathname).ext;
        //         // if the file is found, set Content-type and send data
        //         res.setHeader('Content-type', mimeType[ext] || 'text/plain');
        //         res.end(data);
        //     }
        // });
    });
开发者ID:roelvanlisdonk,项目名称:dev,代码行数:54,代码来源:service.ts

示例4: asyncTest

asyncTest("gzip roundtrip", 1, (_) => {
	const sampleReader1 = ez.devices.file.text.reader(sample);
	var sampleReader2 = ez.devices.file.text.reader(sample);
	const stringify = ez.mappers.convert.stringify();
	const cutter = ez.transforms.cut.transform(10);
	const out = require('fs').createWriteStream(__dirname + '/../../test/fixtures/rss-sample.zip');
	sampleReader2 = sampleReader2.nodeTransform(zlib.createGzip()).nodeTransform(zlib.createGunzip()).map(stringify);
	const cmp = sampleReader1.transform(cutter).compare(_, sampleReader2.transform(cutter));
	equal(cmp, 0);
	start();
});
开发者ID:Sage,项目名称:ez-streams,代码行数:11,代码来源:nodify-test.ts

示例5: reject

  return new Promise<void>((resolve, reject) => {
    const smaller = zlib.createGzip({ level: 9 });
    const input = fs.createReadStream(dbFileNamePath);
    const output = fs.createWriteStream(syncFileNamePath);

    input
      .pipe(smaller)
      .pipe(output)
      .on("error", (err: any) => {
        logger.error("Error: creating warp sync file");
        reject(err);
      })
      .on("finish", () => {
        resolve();
      });
  });
开发者ID:AugurProject,项目名称:augur_node,代码行数:16,代码来源:file-operations.ts

示例6: serveFile

export async function serveFile(devServerConfig: d.DevServerConfig, fs: d.FileSystem, req: d.HttpRequest, res: http.ServerResponse) {
  try {
    if (isSimpleText(req.filePath)) {
      // easy text file, use the internal cache
      let content = await fs.readFile(req.filePath);

      if (isHtmlFile(req.filePath) && !isDevServerClient(req.pathname)) {
        // auto inject our dev server script
        content += injectDevServerClient();

      } else if (isCssFile(req.filePath)) {
        content = updateStyleUrls(req.url, content);
      }

      const contentLength = Buffer.byteLength(content, 'utf8');

      if (shouldCompress(devServerConfig, req, contentLength)) {
        // let's gzip this well known web dev text file
        res.writeHead(200, responseHeaders({
          'Content-Type': getContentType(devServerConfig, req.filePath)
        }));
        zlib.createGzip().pipe(res);

      } else {
        // let's not gzip this file
        res.writeHead(200, responseHeaders({
          'Content-Type': getContentType(devServerConfig, req.filePath),
          'Content-Length': contentLength
        }));
        res.write(content);
        res.end();
      }

    } else {
      // non-well-known text file or other file, probably best we use a stream
      // but don't bother trying to gzip this file for the dev server
      res.writeHead(200, responseHeaders({
        'Content-Type': getContentType(devServerConfig, req.filePath),
        'Content-Length': req.stats.size
      }));
      fs.createReadStream(req.filePath).pipe(res);
    }

  } catch (e) {
    serve500(res, e);
  }
}
开发者ID:franktopel,项目名称:stencil,代码行数:47,代码来源:serve-file.ts

示例7: Buffer

 conn.query(q, args, (qerr, results) => {
     conn.release();
     if (qerr) {
         console.log('Error validating file id', qerr);
         return res.status(500).send({ Error: 'Internal Server Error' });
     }
     if (results.length < 1) {
         return res.send(404).send({ Error: 'No such file ID' });
     }
     const cipher = crypto.createCipher('aes256', new Buffer(APP_CONFIG.storage_key, 'base64'));
     let pl = req.pipe(zlib.createGzip()).pipe(cipher);
     store.store(fileid, pl, function (perr) {
         if (perr) {
             return res.status(500).send({ Error: perr });
         }
         return res.send({ Success: true });
     });
 });
开发者ID:TetuSecurity,项目名称:Crypt,代码行数:18,代码来源:files.ts

示例8: stream_readable_pipe_test

// http://nodejs.org/api/stream.html#stream_readable_pipe_destination_options
function stream_readable_pipe_test() {
    const rs = createReadStream(Buffer.from('file.txt'));
    const r = createReadStream('file.txt');
    const z = createGzip({ finishFlush: constants.Z_FINISH });
    const w = createWriteStream('file.txt.gz');

    assert(typeof z.bytesRead === 'number');
    assert(typeof r.bytesRead === 'number');
    assert(typeof r.path === 'string');
    assert(rs.path instanceof Buffer);

    r.pipe(z).pipe(w);

    z.flush();
    r.close();
    z.close();
    rs.close();
}
开发者ID:CNBoland,项目名称:DefinitelyTyped,代码行数:19,代码来源:stream.ts

示例9: it

 it('should process x-www-form-urlencoded with gzip encoding', async function () {
   const req = new PassThrough();
   const stream = req.pipe(createGzip());
   (stream as any).headers = {
     'content-type': 'application/x-www-form-urlencoded',
     'content-encoding': 'gzip',
     'content-length': 29
   };
   (stream as any).method = 'GET';
   (stream as any).url = '/upload';
   req.end('name=thatiq&key=value&abc=xyz');
   const ctx = W.createHttpContext(stream as any);
   await T.toPromise(middleware(simpleApp)(ctx, T.pure));
   assert.deepEqual(ctx.state.body, {
     name: 'thatiq',
     key: 'value',
     abc: 'xyz'
   });
 });
开发者ID:syaiful6,项目名称:jonggrang,代码行数:19,代码来源:form-fields.ts

示例10: Promise

  return new Promise((resolve, reject) => {
    const pack = tarStream.pack()

    const outDir = path.dirname(outFile)
    if (!fs.existsSync(outDir)) {
      fs.mkdirpSync(outDir)
    }

    for (const { rootDir, files } of manifest) {
      for (const file of files) {
        const stat = fs.statSync(file)
        if (!stat.isFile()) {
          continue
        }
        const name = path.relative(rootDir, file)
        pack.entry({ name }, fs.readFileSync(file))
      }
    }

    pack.finalize()
    const gzip = zlib.createGzip()
    const outStream = fs.createWriteStream(outFile)
    const bundleHash = createHash("sha1").setEncoding("hex")
    pack.pipe(bundleHash)
    const gzStream = pack.pipe(gzip)
    gzStream.pipe(outStream)

    gzStream.on("end", () => {
      bundleHash.end()
      outStream.end()

      resolve({
        path: outFile,
        digest: bundleHash.read().toString(),
        byteLength: outStream.bytesWritten
      })
    })
  })
开发者ID:dianpeng,项目名称:fly,代码行数:38,代码来源:tarball.ts


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