// Check if 'utf-8' is a valid encoding const isValidEncoding = Buffer.isEncoding('utf-8'); console.log(isValidEncoding); // true // Check if 'blah' is a valid encoding const isValidEncoding2 = Buffer.isEncoding('blah'); console.log(isValidEncoding2); // false
function isEncodingSupported(encoding) { if (!Buffer.isEncoding(encoding)) { console.log(`Encoding ${encoding} is not supported.`); return false; } return true; } // Check if 'utf-8' and 'utf-16' are supported encodings const validEncoding1 = isEncodingSupported('utf-8'); // true const validEncoding2 = isEncodingSupported('utf-16'); // true const validEncoding3 = isEncodingSupported('blah'); // falseIn this example, we define a function isEncodingSupported that takes an encoding as a parameter and returns a boolean indicating if the encoding is supported or not. If the encoding is not supported, the function logs a message to the console and returns false. We then call this function to check if 'utf-8', 'utf-16' and 'blah' are supported encodings. The first two calls return true, while the third call returns false. Package library: Node.js