1'use strict'; 2 3const common = require('../common'); 4const { deepStrictEqual, throws } = require('assert'); 5const { runInNewContext } = require('vm'); 6 7const checkString = 'test'; 8 9const check = Buffer.from(checkString); 10 11class MyString extends String { 12 constructor() { 13 super(checkString); 14 } 15} 16 17class MyPrimitive { 18 [Symbol.toPrimitive]() { 19 return checkString; 20 } 21} 22 23class MyBadPrimitive { 24 [Symbol.toPrimitive]() { 25 return 1; 26 } 27} 28 29deepStrictEqual(Buffer.from(new String(checkString)), check); 30deepStrictEqual(Buffer.from(new MyString()), check); 31deepStrictEqual(Buffer.from(new MyPrimitive()), check); 32deepStrictEqual( 33 Buffer.from(runInNewContext('new String(checkString)', { checkString })), 34 check 35); 36 37[ 38 {}, 39 new Boolean(true), 40 { valueOf() { return null; } }, 41 { valueOf() { return undefined; } }, 42 { valueOf: null }, 43 Object.create(null), 44 new Number(true), 45 new MyBadPrimitive(), 46 Symbol(), 47 5n, 48 (one, two, three) => {}, 49 undefined, 50 null, 51].forEach((input) => { 52 const errObj = { 53 code: 'ERR_INVALID_ARG_TYPE', 54 name: 'TypeError', 55 message: 'The first argument must be of type string or an instance of ' + 56 'Buffer, ArrayBuffer, or Array or an Array-like Object.' + 57 common.invalidArgTypeHelper(input) 58 }; 59 throws(() => Buffer.from(input), errObj); 60 throws(() => Buffer.from(input, 'hex'), errObj); 61}); 62 63Buffer.allocUnsafe(10); // Should not throw. 64Buffer.from('deadbeaf', 'hex'); // Should not throw. 65