Core Module Extensions
GZIP Compression
const fs = require('fs');
const zlib = require('zlib');
const compressFile = (inputPath) => {
fs.createReadStream(inputPath)
.pipe(zlib.createGzip())
.pipe(fs.createWriteStream(inputPath + '.compressed'));
};
const decompressFile = (compressedPath) => {
const outputName = compressedPath.replace('.compressed', '');
fs.createReadStream(compressedPath)
.pipe(zlib.createGunzip())
.pipe(fs.createWriteStream(outputName));
};
// compressFile('./document.txt');
decompressFile('./document.txt.compressed');
Crypto Security
const crypto = require('crypto');
// Hash generation
const hashGenerator = crypto.createHmac('sha256', 'secret-key');
hashGenerator.update('data');
hashGenerator.update('stream');
console.log(hashGenerator.digest('hex'));
// Encryption/Decryption
const encryptData = (plainText, secret) => {
const encryptor = crypto.createCipher('aes-256-cbc', secret);
encryptor.update(plainText, 'utf8');
return encryptor.final('hex');
};
const decryptData = (encryptedText, secret) => {
const decryptor = crypto.createDecipher('aes-256-cbc', secret);
decryptor.update(encryptedText, 'hex');
return decryptor.final('utf8');
};
const encrypted = encryptData('secure message', 'password123');
const decrypted = decryptData(encrypted, 'password123');
console.log(decrypted);
Error Handling
process.on('uncaughtException', (error) => {
console.error('Unhandled error:', error.message);
});
setTimeout(() => {
console.log('Application continues');
}, 2000);
throw new Error('Test exception');
Deatched Processes
const { spawn } = require('child_process');
const fs = require('fs');
const logFile = fs.openSync('./process.log', 'w');
const child = spawn('node', ['worker.js'], {
stdio: ['ignore', logFile, 'ignore'],
detached: true,
cwd: __dirname
});
child.unref();
// worker.js
let count = 0;
const interval = setInterval(() => {
console.log(`Process running: ${new Date().toISOString()}`);
if (count++ >= 5) {
clearInterval(interval);
}
}, 500);
Process Forking
const { fork } = require('child_process');
const childProcess = fork('child.js', ['parameter'], {
cwd: __dirname,
silent: false
});
childProcess.on('message', (data) => {
console.log('Parent received:', data);
});
childProcess.send({ payload: 'data' });
// child.js
process.stdout.write('Child process: ' + process.argv[2]);
process.on('message', (msg) => {
process.send(`Child processed: ${JSON.stringify(msg)}`);
});
Command Exceution
const { exec } = require('child_process');
exec('node processor.js arg1 arg2', {
cwd: __dirname,
encoding: 'utf8'
}, (error, stdout, stderr) => {
if (error) console.error('Error:', error);
console.log('Output:', stdout);
});
// processor.js
process.argv.slice(2).forEach(arg => {
console.log(`Argument: ${arg}`);
});
File Execution
const { execFile } = require('child_process');
execFile('node', ['processor.js', 'input1', 'input2'], {
cwd: __dirname
}, (error, stdout) => {
console.log('Result:', stdout);
});
HTTP Headers and Proxies
const http = require('http');
const { createProxyServer } = require('http-proxy');
const proxy = createProxyServer();
const server = http.createServer((req, res) => {
proxy.web(req, res, { target: 'http://localhost:8081' });
}).listen(8080);
// Target server
http.createServer((req, res) => {
res.end('Proxied response');
}).listen(8081);
User Agent Parsing
const http = require('http');
const userAgentParser = require('user-agent-parser');
http.createServer((req, res) => {
const ua = req.headers['user-agent'];
const parsed = userAgentParser(ua);
res.end(JSON.stringify(parsed, null, 2));
}).listen(3000);