How to access environment variables
process.env.USER_ID;
Print stack trace to a console
console.trace()
Start and stop timer, print time to the console
console.time("doSomething()");
console.timeEnd("doSomething()");Create path object from a string
const parsed = path.parse("/users/john/project/file.txt")
Get filename from "/etc/test/file.txt (file.txt)
path.basename("/etc/test/file.txt")
Create path string from components [\_\_dirname, "test", "hello.html"]
path.join(\_\_dirname, "test", "hello.html")
Remove obsolete ../ from "/users/joe/..//test.txt"
path.normalize("/users/joe/..//test.txt");
How to use async fs methods
import fs from "node:fs/promises";
Write or read entire file having fh handle ready
await fh.writeFile("Overwrite content");
const content = await fh.readFile({ encoding: "utf8" });Get user home directory
import os from "node:os";os.homedir();
Create URL object from a string, what you need to import
const myUrl = new URL(
"http://mywebsite.com:5000/hello.html?id=100&status=active"
)
Nothing to import, it is global constructor
What is nodeJS Event Emitter, how to use it (what to import, sample code)
Built-in observer pattern implementation,
import EventEmitter from "node:events";
const eventEmitter = new EventEmitter();
eventEmitter.on("start", (start, end) => console.log("started"));
eventEmitter.emit("start", 1, 100); // Can use any string for event identificationCreate empty Buffer of 1024 bytes.
const buf = Buffer.alloc(1024);
Create Buffer from string Hey
const buf = Buffer.from("Hey!");
Access first byte of a Buffer
buf[0];
How to force NodeJS production mode
NODE_ENV=production
Read file handle fh line by line and print each line.
fh.readLines() returns an async iterable so we need to use for await loop!
for await (const line of fh.readLines()) {
console.log(line);
}Open file (get fh) in write mode
const fh = await fs.open("temp.txt", "w");
Convert Buffer buf to UTF-8 string
buf.toString();
What are Streams in NodeJS, give sample streams in NodeJS API
EventEmitter, can use events to read and write data.Sample streams:
- fs.ReadStream
- http.IncomingMessage when reading HTTP requests.
- process.stdin
- fs.WriteStream
- process.stdout
- process.stderr
How to create a pipeline with streams (like linux readableSrc | t1 | t2 | final). Show both methods
pipe - legacy
readableSrc.pipe(t1).pipe(t2).pipe(final);
pipeline This method is a safer and more robust way to pipe streams together, handling errors and cleanup automatically.
pipeline(readStream, upper, writeStream, (err) => {
if (err) {
return console.error("Pipeline error:", err.message);
}
console.log("Pipeline succeeded");
});
// In case of error, all streams will be closed.What is backpressure in nodejs streams
Backpressure (Buffering)
highWaterMark or the write queue is currently busy, .write() will return false.false value is returned, the backpressure system kicks in. It will pause the incoming Readable stream from sending any data and wait until the consumer is ready again.'drain' event will be emitted to resume the incoming data flow.