2

I am trying to send an http response in node to print results in the browser. The simplified source code is down below. Basically, all the variables are defined somewhere in the program, so that shouldn't be problem. When I try to run the script, I keep getting the error:

    http.js:783
        throw new TypeError('first argument must be a string or Buffer');

    TypeError: first argument must be a string or Buffer

So can someone familiar with node.js or javascript syntax let me know what the problem is?

    upload = function(req, res) {
        var fileInfos = [obj, obj];    //defined as an array of objects
        var counter = 0;           
        counter -= 1;
        if (!counter) {                
            res.end({files: fileInfos});    //files is defined. 
        }
        };

    async.forEach(urls, downloadFile, function (err) {    //all params defined. 
        if(err){
            console.error("err");
            throw err;
        }
        else{
            http.createServer(function(req, res){
            upload(req1, res);                       //req1 defined as an array of objects.
        }).listen(3000, "127.0.0.1");
        console.log('Server running at http://127.0.0.1:3000/');
    }
    });

2 Answers 2

1

This error is often caused by an attempt to call response.write with the wrong type of parameter. Looking at the documentation it suggests:

response.end([data], [encoding])#

This method signals to the server that all of the response headers and body have been sent; that server should consider this message complete. The method, response.end(), MUST be called on each response.

If data is specified, it is equivalent to calling response.write(data, encoding) followed by response.end().

Now response.write( chunk, encoding ) expects the chunk to be a string, so it seems possible that when you are calling res.end({files: fileInfos}) it is unable to write the content of that object as a string.

Sign up to request clarification or add additional context in comments.

Comments

1

You can use JSON.stringify() to convert the JavaScript object to string before sending it to the client.

res.end(JSON.stringify({files: fileInfos}));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.