简体   繁体   中英

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 Object | MyOwnObject ?

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

Thanks.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM