Globals & Buffer

Globals and Bufferes

1. Global Objects


In Node.js, Globals are variables, functions, and objects that are available in all modules without having to use require() or import.


The global Object

The global object is the equivalent of the window object in browsers. Anything attached to global is accessible everywhere.


Common Global Variables:


  • __dirname  : Provides the absolute path to the directory containing the current file.

  • __filename : Provides the absolute path to the current file (including the filename).

  • process    : One of the most important globals. It provides info about the current Node.js process (e.g., process.env, process.exit(), process.argv).

  • module, exports, and require(): Used for the module system (CommonJS).


Note: __dirname and __filename are technically "module-level globals"—they look like globals, but they are actually specific to each file.


2. Buffers


Computers don't communicate in "strings" or "images"—they communicate in Binary (0s and 1s). While JavaScript is great at handling strings, it historically struggled with raw binary data.


A Buffer is a dedicated chunk of memory outside the V8 heap used to hold raw binary data.


Why do we need Buffers?


When you are doing things like:

  1. Reading a file from the hard drive.

  2. Receiving packets of data over a network.

  3. Processing an image or a video.


The data arrives in "chunks." A Buffer acts as a "waiting room" for this data until the program is ready to process it.


3. Working with Buffers (Code Snippets)


// Create an empty buffer of 10 bytes
const buf1 = Buffer.alloc(10);

// Create a buffer from a string
const buf2 = Buffer.from("Hello Careeroza");

console.log(buf2); 
// Output: <Buffer 48 65 6c 6c 6f 20 43 61 72 65 65 72 6f 7a 61>

Converting back to String

console.log(buf2.toString()); // Output: Hello Careeroza