首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用fetch-mock模拟zip响应

使用fetch-mock模拟zip响应
EN

Stack Overflow用户
提问于 2017-01-22 05:42:14
回答 1查看 625关注 0票数 5

我试过使用以下代码:

代码语言:javascript
复制
require( 'isomorphic-fetch' );

const fetchMock = require( 'fetch-mock' ),
    fsp = require( 'fs-promise' ),
    unzip = require( 'unzip' ),
    rimraf = require( 'rimraf-then' ),
    path = require( 'path' );

let zipLink = 'https://github.com/stevemao/left-pad/archive/master.zip',
    out = 'left-pad-master';

// Careful: lib might be removed at any moment.
fetchMock.get( zipLink,
    fsp.createReadStream( path.join( __dirname, 'left-pad-master.zip' ) ) );

rimraf( out )
    .then( () => fetch( zipLink ) )
    .then( response => {
        return new Promise( ( resolve, reject ) => {
            // For example purpose, just parse zip file, and log each entry.
            response.body.pipe( unzip.Parse() )
                .on( 'entry', ( entry ) => console.log( entry.path ) )
                .on( 'close', resolve )
                .on( 'error', reject );
        } );
    } )
    .then( () => console.log( 'done' ) )
    .catch( console.log );

但是它抛出了:

代码语言:javascript
复制
Error: invalid signature: 0x725f227b
    at C:\dev\unzip-mock\node_modules\unzip\lib\parse.js:59:13
    at runCallback (timers.js:628:20)
    at tryOnImmediate (timers.js:601:5)
    at processImmediate [as _immediateCallback] (timers.js:578:5)

如果你注释掉fetchMock.get调用,并使用真正的fetch,它会工作得很好。

代码可以在https://github.com/mlewand/unzip-mock-example上找到

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-01-29 07:33:10

将一个Response实例作为第二个参数传递给fetchMock.get(),其中响应对象的body为本地文件流:

代码语言:javascript
复制
require( 'isomorphic-fetch' );

const fetchMock = require( 'fetch-mock' ),
    fsp = require( 'fs-promise' ),
    unzip = require( 'unzip' ),
    rimraf = require( 'rimraf-then' ),
    path = require( 'path' );

let zipLink = 'https://github.com/stevemao/left-pad/archive/master.zip',
    out = 'left-pad-master';

// Careful: lib might be removed at any moment.
var resp = new Response(
    fsp.createReadStream( path.join( __dirname, 'left-pad-master.zip' ) ),
    { headers: { "Content-Type" : "application/zip" } }
);
fetchMock.get(zipLink, resp);

rimraf( out )
    .then( () => fetch( zipLink ) )
    .then( response => {
        return new Promise( ( resolve, reject ) => {
            // For example purpose, just parse zip file, and log each entry.
            response.body.pipe( unzip.Parse() )
                .on( 'entry', ( entry ) => console.log( entry.path ) )
                .on( 'close', resolve )
                .on( 'error', reject );
        } );
    } )
    .then( () => console.log( 'done' ) )
    .catch( console.log );
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/41784848

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档