Aman
Aman

Reputation: 35

throw new TypeError('first argument must be a string or Buffer') in node.js

I'm new to node js and started learning a week ago.

While creating a small server I got the below error:

_http_outgoing.js:543 throw new TypeError('first argument must be a string or Buffer'); ^

TypeError: first argument must be a string or Buffer at ServerResponse.OutgoingMessage.end (_http_outgoing.js:543:11) at call_backfunction (/Users/Aman/Documents/learn/node/app3/server.js:36:8) at iterator (/Users/Aman/Documents/learn/node/app3/server.js:57:6) at /Users/Aman/Documents/learn/node/app3/server.js:68:6 at FSReqWrap.oncomplete (fs.js:82:15)

function loadAlbums(req, res){
    var call_backfunction = function(err, album_list){
        if(err){
            res.writeHead(503, {"Content-Type": "text/plain"});
            res.end("There are no albums in folder. " + err + "\n");
        }
        else{
            res.writeHead(200, {"Content-Type": "text/json"});
            res.end(album_list);
        }
    }

    albumLoader(req, res, call_backfunction);
}


function albumLoader(req, res, callback){
    var path = req.core_url.pathname.substr(1, 6);
    fs.readdir(path, function(err, files){
        if(err){
            callback(err);
            return;
        }   
        else{
            var dirs = [];
            (function iterator(i) {
                console.log(dirs);
                if(i>=files.length){
                    callback(null, dirs);
                    return;
                }
                fs.stat(path + "/" + files[i], function(err, stat){
                    if(err){
                        callback(err);
                        return;
                    }
                    else if(stat.isDirectory){
                        dirs.push(files[i]);
                    }
                    iterator(i+1);
                });
            })(0);          
        }
    });
}

Its working fine when I change callback parameter to

callback(null, dirs.toString());

I really didn't understand the logic here, why it needs string or buffer.

Upvotes: 2

Views: 18107

Answers (1)

piscator
piscator

Reputation: 8709

res.end(data) (with the data argument specified) is an equivalent of res.write() and res.end(). res.write() only accepts a string or Buffer as it's argument. Read more here.

When you run this code, album_list is an array.

res.end(album_list);

After converting the dirs array, and consequently the album_list argument to a Buffer or a string you will not get this error.

It has to be a string or Buffer because the default encoding of the response body is utf8 character encoding.

Upvotes: 4

Related Questions