这是我从官方文档中获得的代码,并进行了一些修改:
let file = fs.createWriteStream( "data/test.txt" );
let httpOptions = "https://google.com";
const req = https.request( httpOptions, ( response ) => {
response.on( 'data', ( chunk ) => {
response.pipe( file );
file.on( "finish", () => {} )
.on( "close", () => { file.close(); } )
.on( "error", ( err ) => { console.log( "!!! Error: " + err ); } );
} );
});
req.on( 'error', (e) => {
console.error(e);
});
req.end();
我在这一行得到:““监听器”参数必须是函数类型”:
.on( "close", () => { file.close(); } )
我做错了什么?我添加了“关闭”处理程序,因此它应该可以正常工作,但事实并非如此。
这是完整的错误:
events.js:180 throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'listener', 'Function'); ^ TypeError [ERR_INVALID_ARG_TYPE]: The "listener" argument must be of type Function at _addListener (events.js:180:11) at WriteStream.addListener (events.js:240:10) at WriteStream.close (fs.js:2298:10) at WriteStream.file.on (/Users/.../myscript.js:229:32) <=== This is .on( "close", () => { file.close(); } ) at WriteStream.emit (events.js:159:13) at fs.close (fs.js:2141:14) at FSReqWrap.oncomplete (fs.js:149:20)
Node.js: 9.3.0_1, MacOS X: 10.12.5
UPD: If I change these lines to new ones:
file.on( "finish", () => { } )
.on( "close", () => { } )
没有任何错误,但输出文件为空。所以 node.js 不允许我正确关闭文件:)
最佳答案
我无法复制错误。如果我从你的问题中获取代码,添加两个 require
调用,然后运行它,我不会收到错误(在 *nix 上,不是 Mac OS,但它们非常相似)。但我也没有在文件中获取数据。
在 data
事件中调用 pipe
没有多大意义。相反:
const fs = require("fs");
const https = require("https");
let file = fs.createWriteStream( "data/test.txt" );
// *** Note moving the code setting up these handlers out of the `data` callback
// That said, since you're using `pipe`, I don't think you need the close handler,
// and your finish handler doesn't do anything
file.on( "finish", () => {} )
.on( "close", () => { file.close(); } )
.on( "error", ( err ) => { console.log( "!!! Error: " + err ); } );
let httpOptions = "https://google.com";
const req = https.request( httpOptions, ( response ) => {
// *** Do the pipe
response.pipe( file );
});
req.on( 'error', (e) => {
console.error(e);
});
req.end();
如果我这样做,我会在文件中获取数据(特别是 302 的文本)。 (我也明白了,没有错误,没有向 file
添加任何处理程序。)
关于javascript - “listener” 参数必须是函数类型。 MacOS 上的 Node.JS 9.3.0_1 有问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48165399/