Clovis Clovis - 4 months ago 5x
Node.js Question

Node type checking / 'coerced to a string'?

Newly to Node.js i would have known how node types really working ...

I'm currently working on files, just to have an example take a look at this function :

fs.write(fd, data[, position[, encoding]], callback)

According to the documentation, data should be of types :

data <String> | <Buffer>

but next it's specified

If data is not a Buffer instance then the value will be coerced to a string.

1 /
I'm asking if data paramater accepted types is pure speculation and it could be of any type like:
Object | MyOwnObject

2 /
In this case, what means 'coerced to a string' ? I mean, Is it calling a toString() method of my object ?



If the data parameter is neither a Buffer nor a String, it is coerced by adding the empty string to it:

if (typeof buffer !== 'string')
    buffer += '';

This is equivalent to

buffer = String(buffer) + '';

In many cases, this will end up calling buffer.toString().

Source: the source code