Node
atob
解码使用 base-64
编码的数据字符串。
使用 base-64
编码为给定字符串创建 Buffer
,并使用 Buffer.toString('binary')
返回已解码的字符串。
const atob = str => Buffer.from(str, 'base64').toString('binary');
atob('Zm9vYmFy'); // 'foobar'
btoa
Creates a base-64 encoded ASCII string from a String object in which each character in the string is treated as a byte of binary data.
Create a Buffer
for the given string with binary encoding and use Buffer.toString('base64')
to return the encoded string.
创建 base-64
编码的 ASCII
字符串,其中字符串中的每个字符都被视为二进制数据的字节。
使用二进制编码为给定字符串创建 Buffer
,并使用 Buffer.toString('base64')
返回编码字符串。
const btoa = str => Buffer.from(str, 'binary').toString('base64');
btoa('foobar'); // 'Zm9vYmFy'
colorize
Add special characters to text to print in color in the console (combined with console.log()
).
Use template literals and special characters to add the appropriate color code to the string output. For background colors, add a special character that resets the background color at the end of the string.
const colorize = (...args) => ({ black: `\x1b[30m${args.join(' ')}`, red: `\x1b[31m${args.join(' ')}`, green: `\x1b[32m${args.join(' ')}`, yellow: `\x1b[33m${args.join(' ')}`, blue: `\x1b[34m${args.join(' ')}`, magenta: `\x1b[35m${args.join(' ')}`, cyan: `\x1b[36m${args.join(' ')}`, white: `\x1b[37m${args.join(' ')}`, bgBlack: `\x1b[40m${args.join(' ')}\x1b[0m`, bgRed: `\x1b[41m${args.join(' ')}\x1b[0m`, bgGreen: `\x1b[42m${args.join(' ')}\x1b[0m`, bgYellow: `\x1b[43m${args.join(' ')}\x1b[0m`, bgBlue: `\x1b[44m${args.join(' ')}\x1b[0m`, bgMagenta: `\x1b[45m${args.join(' ')}\x1b[0m`, bgCyan: `\x1b[46m${args.join(' ')}\x1b[0m`, bgWhite: `\x1b[47m${args.join(' ')}\x1b[0m` });
向文本中添加特殊字符,以便在控制台中以彩色方式打印(与 console.log()
结合)。
使用模板字面量和特殊字符将相应的颜色代码添加到字符串输出中。 对于有背景颜色的,添加一个特殊字符,在字符串的末尾重置背景颜色。
console.log(colorize('foo').red); // 'foo' (red letters) console.log(colorize('foo', 'bar').bgBlue); // 'foo bar' (blue background) console.log(colorize(colorize('foo').yellow, colorize('foo').green).bgWhite); // 'foo bar' (first word in yellow letters, second word in green letters, white background for both)
createDirIfNotExists
Creates a directory, if it does not exist.
Use fs.existsSync()
to check if the directory exists, fs.mkdirSync()
to create it.
const fs = require('fs'); const createDirIfNotExists = dir => (!fs.existsSync(dir) ? fs.mkdirSync(dir) : undefined);
createDirIfNotExists('test'); // creates the directory 'test', if it doesn't exist
hasFlags
Check if the current process's arguments contain the specified flags.
Use Array.prototype.every()
and Array.prototype.includes()
to check if process.argv
contains all the specified flags. Use a regular expression to test if the specified flags are prefixed with -
or --
and prefix them accordingly.
const hasFlags = (...flags) => flags.every(flag => process.argv.includes(/^-{1,2}/.test(flag) ? flag : '--' + flag));
// node myScript.js -s --test --cool=true hasFlags('-s'); // true hasFlags('--test', 'cool=true', '-s'); // true hasFlags('special'); // false
hashNode
Creates a hash for a value using the SHA-256 algorithm. Returns a promise.
Use crypto
API to create a hash for the given value, setTimeout
to prevent blocking on a long operation, and a Promise
to give it a familiar interface.
const crypto = require('crypto'); const hashNode = val => new Promise(resolve => setTimeout( () => resolve( crypto .createHash('sha256') .update(val) .digest('hex') ), 0 ) );
hashNode(JSON.stringify({ a: 'a', b: [1, 2, 3, 4], foo: { c: 'bar' } })).then(console.log); // '04aa106279f5977f59f9067fa9712afc4aedc6f5862a8defc34552d8c7206393'
isDuplexStream
Checks if the given argument is a duplex (readable and writable) stream.
Check if the value is different from null
, use typeof
to check if a value is of type object
and the pipe
property is of type function
. Additionally check if the typeof
the _read
, _write
and _readableState
, _writableState
properties are function
and object
respectively.
const isDuplexStream = val => val !== null && typeof val === 'object' && typeof val.pipe === 'function' && typeof val._read === 'function' && typeof val._readableState === 'object' && typeof val._write === 'function' && typeof val._writableState === 'object';
const Stream = require('stream'); isDuplexStream(new Stream.Duplex()); // true
isReadableStream
Checks if the given argument is a readable stream.
Check if the value is different from null
, use typeof
to check if the value is of type object
and the pipe
property is of type function
. Additionally check if the typeof
the _read
and _readableState
properties are function
and object
respectively.
const isReadableStream = val => val !== null && typeof val === 'object' && typeof val.pipe === 'function' && typeof val._read === 'function' && typeof val._readableState === 'object';
const fs = require('fs'); isReadableStream(fs.createReadStream('test.txt')); // true
isStream
Checks if the given argument is a stream.
Check if the value is different from null
, use typeof
to check if the value is of type object
and the pipe
property is of type function
.
const isStream = val => val !== null && typeof val === 'object' && typeof val.pipe === 'function';
const fs = require('fs'); isStream(fs.createReadStream('test.txt')); // true
Recommended Resource - JavaScript: The Hard Parts
Take your JavaScript to the next level. Gain an understanding of callbacks, higher order functions, closure, asynchronous and object-oriented JavaScript!
isTravisCI
Checks if the current environment is Travis CI.
Checks if the current environment has the TRAVIS
and CI
environment variables (reference).
const isTravisCI = () => 'TRAVIS' in process.env && 'CI' in process.env;
isTravisCI(); // true (if code is running on Travis CI)
isWritableStream
Checks if the given argument is a writable stream.
Check if the value is different from null
, use typeof
to check if the value is of type object
and the pipe
property is of type function
. Additionally check if the typeof
the _write
and _writableState
properties are function
and object
respectively.
const isWritableStream = val => val !== null && typeof val === 'object' && typeof val.pipe === 'function' && typeof val._write === 'function' && typeof val._writableState === 'object';
const fs = require('fs'); isWritableStream(fs.createWriteStream('test.txt')); // true
JSONToFile
Writes a JSON object to a file.
Use fs.writeFile()
, template literals and JSON.stringify()
to write a json
object to a .json
file.
const fs = require('fs'); const JSONToFile = (obj, filename) => fs.writeFile(`${filename}.json`, JSON.stringify(obj, null, 2));
JSONToFile({ test: 'is passed' }, 'testJsonFile'); // writes the object to 'testJsonFile.json'
readFileLines
Returns an array of lines from the specified file.
Use readFileSync
function in fs
node package to create a Buffer
from a file. convert buffer to string using toString(encoding)
function. creating an array from contents of file by split
ing file content line by line (each \n
).
const fs = require('fs'); const readFileLines = filename => fs .readFileSync(filename) .toString('UTF8') .split('\n');
/* contents of test.txt : line1 line2 line3 ___________________________ */ let arr = readFileLines('test.txt'); console.log(arr); // ['line1', 'line2', 'line3']
untildify
Converts a tilde path to an absolute path.
Use String.prototype.replace()
with a regular expression and OS.homedir()
to replace the ~
in the start of the path with the home directory.
const untildify = str => str.replace(/^~($|\/|\\)/, `${require('os').homedir()}$1`);
untildify('~/node'); // '/Users/aUser/node'
UUIDGeneratorNode
Generates a UUID in Node.JS.
Use crypto
API to generate a UUID, compliant with RFC4122 version 4.
const crypto = require('crypto'); const UUIDGeneratorNode = () => ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c => (c ^ (crypto.randomBytes(1)[0] & (15 >> (c / 4)))).toString(16) );
UUIDGeneratorNode(); // '79c7c136-60ee-40a2-beb2-856f1feabefc'