Skip to content

Instantly share code, notes, and snippets.

@tsmx
tsmx / json-traverse.js
Last active September 22, 2020 19:32
Traversing a JSON object in JavaScript for printing it out or applying functions/filters to every key/value - tracks the full path of every element, supports arrays, nested objects, arrays-in-arrays and objects-in-arrays
// the sample simply logs every item with its corresponding path
// replace 'logKeyValue' with custom functions/filters/... that should be applied
function traverse(obj, path = []) {
Object.entries(obj).forEach(([key, val]) => {
if (val !== null && typeof val == 'object') {
if (Array.isArray(val)) {
for (let i = 0; i < val.length; i++) {
let elem = val[i];
let itemKey = createKeyString(i, true);
@tsmx
tsmx / streamutils.js
Last active November 9, 2020 19:14
NodeJS: convert stream to buffer and vice versa
const Readable = require('stream').Readable;
// stream-to-buffer promise variant
module.exports.streamToBufferPromise = function (stream) {
return new Promise((resolve, reject) => {
var bufs = [];
var buffer = null;
stream.on('error', (error) => { reject(error); });
stream.on('data', (data) => { bufs.push(data); });
stream.on('end', () => {
@tsmx
tsmx / process-exit.test.js
Last active August 9, 2020 19:25
Jest: properly test a function branch ending in process.exit, e.g. in a CLI app
const myFunc = function (condition) {
console.log('before');
if (condition) {
process.exit(-1);
}
console.log('after');
}
describe('jest-process-exit test suite', () => {
@tsmx
tsmx / jest.config.js
Created August 9, 2020 19:05
Jest: set environment variable for all tests via configuration file
// MY_VAR is available in all Jest tests and suites, no need to adapt the before() or beforeAll() functions
process.env['MY_VAR'] = 'My-Var-value';
module.exports = {
testEnvironment: 'node'
};