NodeJS Flashcards
(21 cards)
NPM: Install specific version (1.2.0)
npm install cowsay@1.2.0
NPM: Remove specific package
npm uninstall cowsay
NPM: Update specific package
npm update cowsay
NPM: All packages for update
npm outdated
NPM: Show all versions of a package
npm view cowsay versions
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
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 and read from a file
await fs.writeFile("message.txt", "content"); // Write entire at once await fs.appendFile("message.txt", " I love Node.js"); // append await fs.readFile("message.txt", "utf8"); // Reads entire file at once
Get user home directory
import os from "node:os";
os.homedir();
Get hostname
import os from "node:os";
os.hostname();
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
NoteJS events that can be listened to or emitted - sort of built-in observer.
```javascript
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 identification
~~~
Create 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];