Home » Node.js Punycode

Node.js Punycode

by Online Tutorials Library

Node.js Punycode


What is Punycode

Punycode is an encoding syntax which is used to convert Unicode (UTF-8) string of characters to basic ASCII string of characters. Since host names only understand ASCII characters so Punycode is used. It is used as an internationalized domain name (IDN or IDNA). Let’s understand it with an example:

Assume if you search for mañana.com in your browser so your browser (which is IDNA enabled) first convert this to punycode xn--maana-pta.com because the character ñ is not allowed in regular domain name. It is not supported in older versions.

Punycode in Node.js

Punycode.js is bundled with Node.js v0.6.2 and later versions. If you want to use it with other Node.js versions then use npm to install punycode module first. You have to use require (‘punycode’) to access it.

Syntax:

punycode.decode(string)

It is used to convert a Punycode string of ASCII symbols to a string of Unicode symbols.

File: punycode_example1.js

Output:

Node.js punycode example 1

punycode.encode(string)

It is used to convert a string of Unicode symbols to a Punycode string of ASCII symbols.

File: punycode_example2.js

Output:

Node.js punycode example 2

punycode.toASCII(domain)

It is used to convert a Unicode string representing a domain name to Punycode. Only the non-ASCII part of the domain name is converted.

File: punycode_example3.js

Output:

Node.js punycode example 3

punycode.toUnicode(domain)

It is used to convert a Punycode string representing a domain name to Unicode. Only the Punycoded part of the domain name is converted.

File: punycode_example4.js

Output:

Node.js punycode example 4

Next TopicNode.js TTY

You may also like