gpt4 book ai didi

node.js - 使用 fetch-mock 模拟 zip 响应

转载 作者:搜寻专家 更新时间:2023-10-31 22:44:56 27 4
gpt4 key购买 nike

我试过以下代码:

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 );

但是它抛出:

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 获得

最佳答案

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

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 );

关于node.js - 使用 fetch-mock 模拟 zip 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41784848/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com