curriculum/challenges/english/blocks/review-node-js-core-modules/69247cd74caa633ccd7e3351.md
require() to import core modules into your application.const fs = require("fs");
const crypto = require("crypto");
const os = require("os");
const fs = require("fs");fs.writeFile("filePath", "content", "utf8", (err) => {
if (err) throw err;
console.log("File written to!");
});
async/await.const fs = require("fs/promises");
async function writeToFile() {
try {
await fs.writeFile("article.md", "## Node fs Module");
console.log("File written to!");
} catch (err) {
console.error(err);
}
}
try {
fs.writeFileSync("article.md", "## Node fs Module", "utf8");
console.log("File written to!");
} catch (err) {
console.error(err);
}
writeFile() Method: Creates or overwrites a file with specified content.await fs.writeFile("article.md", "## Node fs Module: The Complete Guide");
appendFile() Method: Adds content to the end of an existing file.await fs.appendFile("article.md", "\n\nIn this article, you will learn...");
readFile() Method: Reads the contents of a file.const content = await fs.readFile("article.md", "utf8");
console.log("File content:", content);
unlink() Method: Deletes a file from the file system.await fs.unlink("article.md");
console.log("File deleted successfully");
"utf8" to read files as text strings.// Returns string
const textContent = await fs.readFile("file.txt", "utf8");
// Returns Buffer
const bufferContent = await fs.readFile("file.txt");
const { Buffer } = require("buffer");Buffer.from() Method: Creates buffer from strings, arrays, or other data.// From string
const myStrBuffer = Buffer.from("freeCodeCamp");
console.log(myStrBuffer); // <Buffer 66 72 65 65 43 6f 64 65 43 61 6d 70>
// From array of numbers
const myNumBuffer = Buffer.from([70, 82, 69, 69, 67, 79, 68, 69, 67, 65, 77, 80]);
Buffer.alloc() Method: Creates buffer of specified size filled with zeros.const someBuffer = Buffer.alloc(10);
console.log(someBuffer); // <Buffer 00 00 00 00 00 00 00 00 00 00>
console.log(myStrBuffer[0]); // 102 (byte value for 'f')
toString() Method: Converts buffer to readable string.console.log(myStrBuffer.toString()); // "freeCodeCamp"
Buffer.write() Method: Writes data to an allocated buffer.someBuffer.write("Hello fCC");
console.log(someBuffer.toString()); // "Hello fCC"
Buffer.byteLength() Method: Returns number of bytes needed to store a string.console.log(Buffer.byteLength("Hello freeCodeCamp")); // 18
Buffer.isBuffer(): Checks if an object is a buffer.Buffer.compare(): Compares two buffers and returns sort order.Buffer.concat(): Joins multiple buffers into one.const crypto = require("crypto");bcrypt or jsonwebtoken for production authentication.createHash() Method: Creates one-way hash using algorithms like SHA256, SHA512, or MD5.const hashedPassword = crypto
.createHash("sha256")
.update("myPassword123")
.digest("hex");
console.log("createHash result:", hashedPassword);
createHmac() Method: Creates a hash with a secret key for authentication and data integrity.const hashedMessage = crypto
.createHmac("sha256", "secret-key")
.update("Hello World")
.digest("hex");
createCipheriv() and createDecipheriv() Methods: Encrypt and decrypt data using algorithms, keys, and initialization vectors.const key = Buffer.from("12345678901234567890123456789012"); // 32 bytes for AES-256
const iv = Buffer.from("1234567890123456"); // 16 bytes for AES
// Encryption
const cipher = crypto.createCipheriv("aes-256-cbc", key, iv);
let encrypted = cipher.update("Hello campers!", "utf8", "hex");
encrypted += cipher.final("hex");
// Decryption
const decipher = crypto.createDecipheriv("aes-256-cbc", key, iv);
let decrypted = decipher.update(encrypted, "hex", "utf8");
decrypted += decipher.final("utf8");
randomBytes() Method: Generates cryptographically secure random bytes.console.log("Random Bytes:", crypto.randomBytes(16).toString("hex"));
// Output: a6154ef5a296fa176ad0f332bd94d712
randomInt() Method: Generates secure random integers within specified range.console.log("Random Int:", crypto.randomInt(0, 100)); // Random number 0-99
createSecretKey() Method: Creates cryptographic key objects from raw bytes.const secret = crypto.createSecretKey(crypto.randomBytes(32));
console.log(secret.export().toString('hex'));
sign() and verify() Methods: Create and validate digital signatures using private/public key pairs.createPublicKey() and createPrivateKey(): Work with externally generated keys.createDiffieHellman(): Enables secure shared secret generation.Certificate(): Handles HTTPS certificate operations.const os = require("os");platform() Method: Returns operating system platform.console.log(os.platform()); // 'darwin', 'win32', 'linux', etc.
// Cross-platform usage
if (os.platform() === 'win32') {
// Windows-specific code
} else {
// Unix-like systems
}
arch() Method: Returns CPU architecture.console.log(os.arch()); // 'arm64', 'x64', 'arm', 'ia32', etc.
type() Method: Returns official operating system name.console.log(os.type()); // 'Darwin', 'Linux', 'Windows_NT'
release() Method: Shows OS kernel version.console.log(os.release()); // '25.0.0'
version() Method: Returns detailed OS version information.console.log(os.version());
// Darwin Kernel Version 25.0.0: Wed Sep 17 21:41:39 PDT 2025
cpus() Method: Returns an array of CPU core information.console.log(os.cpus()); // Array of CPU core objects with model, speed, times
uptime() Method: Returns system uptime in seconds.console.log(os.uptime()); // 23047 (seconds since system boot)
totalmem() Method: Returns total system memory in bytes.freemem() Method: Returns available system memory in bytes.async/await with promises-based API for cleaner, maintainable code.path module for cross-platform file path operations.Review the Node.js Core Modules topics and concepts.