Node.js Data

Node code often moves between JavaScript objects, arrays, JSON payloads, and binary buffers. Knowing the difference keeps APIs predictable.

Objects and arrays

Plain objects model keyed records (entities, configuration, request bodies), while arrays hold ordered sequences. Prefer non-mutating operations (object spread { ...user }, map, filter) when transforming shared data so callers are not surprised by side effects:

const user = { name: "Ada", active: true };
const tags = ["api", "node", "lab"];
// Shallow copy with updated property; original `user` stays unchanged
const updated = { ...user, active: false };
console.log(updated, tags.length);

JSON

JSON is the primary wire format for HTTP APIs and configuration files. Because JSON.parse() throws a SyntaxError on malformed input, always wrap untrusted payloads in try / catch and validate required fields before using them:

function parsePayload(raw) {
  try {
    return JSON.parse(raw);
  } catch (err) {
    throw new Error(`Invalid JSON payload: ${err.message}`);
  }
}

const text = JSON.stringify({ ok: true, count: 3 });
console.log(parsePayload(text));

Buffers

A Buffer is Node's fixed-size raw binary allocation (a subclass of Uint8Array). Unlike JavaScript UTF-16 strings, Buffers store exact bytes for file I/O, cryptography, compression, and network sockets. Always use Buffer.from() or Buffer.alloc() (which zero-fills memory) rather than deprecated unsafe constructors:

const buf = Buffer.from("hello", "utf8");
console.log(buf.toString("hex"));   // "68656c6c6f"
console.log(buf.byteLength);        // 5 bytes

Practice

Work with objects, JSON, and binary buffers in a short script:

  1. Create a user object, clone it with spread syntax while updating one field, and verify the original is unchanged.
  2. Write a safe parsePayload helper with try / catch and test it with both valid and invalid JSON strings.
  3. Encode a UTF-8 string containing an emoji into a Buffer and compare str.length against buf.byteLength.