On this page

    M

    v8.isStringOneByteRepresentation

    History
    v8.isStringOneByteRepresentation(content): boolean
    Attributes
    content:string
    Returns:boolean

    V8 only supports Latin-1/ISO-8859-1 and UTF16 as the underlying representation of a string. If the content uses Latin-1/ISO-8859-1 as the underlying representation, this function will return true; otherwise, it returns false.

    If this method returns false, that does not mean that the string contains some characters not in Latin-1/ISO-8859-1. Sometimes a Latin-1 string may also be represented as UTF16.

    import { isStringOneByteRepresentation } from 'node:v8';
    import { Buffer } from 'node:buffer';
    
    const Encoding = {
      latin1: 1,
      utf16le: 2,
    };
    const buffer = Buffer.alloc(100);
    function writeString(input) {
      if (isStringOneByteRepresentation(input)) {
        console.log(`input: '${input}'`);
        buffer.writeUint8(Encoding.latin1);
        buffer.writeUint32LE(input.length, 1);
        buffer.write(input, 5, 'latin1');
        console.log(`decoded: '${buffer.toString('latin1', 5, 5 + input.length)}'\n`);
      } else {
        console.log(`input: '${input}'`);
        buffer.writeUint8(Encoding.utf16le);
        buffer.writeUint32LE(input.length * 2, 1);
        buffer.write(input, 5, 'utf16le');
        console.log(`decoded: '${buffer.toString('utf16le', 5, 5 + input.length * 2)}'`);
      }
    }
    writeString('hello');
    writeString('你好');
    const { isStringOneByteRepresentation } = require('node:v8');
    const { Buffer } = require('node:buffer');
    
    const Encoding = {
      latin1: 1,
      utf16le: 2,
    };
    const buffer = Buffer.alloc(100);
    function writeString(input) {
      if (isStringOneByteRepresentation(input)) {
        console.log(`input: '${input}'`);
        buffer.writeUint8(Encoding.latin1);
        buffer.writeUint32LE(input.length, 1);
        buffer.write(input, 5, 'latin1');
        console.log(`decoded: '${buffer.toString('latin1', 5, 5 + input.length)}'\n`);
      } else {
        console.log(`input: '${input}'`);
        buffer.writeUint8(Encoding.utf16le);
        buffer.writeUint32LE(input.length * 2, 1);
        buffer.write(input, 5, 'utf16le');
        console.log(`decoded: '${buffer.toString('utf16le', 5, 5 + input.length * 2)}'`);
      }
    }
    writeString('hello');
    writeString('你好');