“listener”参数必须是Function类型。 MacOS上的Node.JS 9.3.0_1有问题

时间:2018-01-09 09:48:55

标签: javascript node.js macos https node-modules

这是我从官方文件中得到的代码,其中有一些我的修改:

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

我得到:"“listener”参数必须是Function"在这一行:

.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: 如果我将这些行改为新行:

file.on( "finish", () => { } )
.on( "close", () => { } )

没有任何错误,但输出文件为空。所以node.js不允许我正确关闭文件:)

2 个答案:

答案 0 :(得分:1)

我无法复制错误。如果我从您的问题中获取代码,请添加两个require来电,并运行它,我不会收到错误(在* nix上,而不是Mac OS,但它们非常相似) 。但我也没有在文件中获取数据。

pipe事件中调用data 并没有多大意义。代替:

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添加任何处理程序。)

答案 1 :(得分:0)

如果仍然存在错误(即使已接受的答案已修复),请尝试从主机中删除https / http。这很奇怪,但是很有意义,因为http或https将根据端口号和所使用的模块等其他因素来决定。