Skip to content

Instantly share code, notes, and snippets.

View WebReflection's full-sized avatar
🎯
Focusing

Andrea Giammarchi WebReflection

🎯
Focusing
View GitHub Profile
// Add module.import to your NodeJS env
// once and on the application entry point only
module.constructor.prototype.import = function (path) {
return Promise.resolve().then(function () {
return this.require(path);
}.bind(this));
};
// multiple import
Promise.all([
module.import('./awe'),
module.import('./some')
]).then(modules => {
const [awe, some] = modules;
});
// export with multiple dependencies
module.exports = Promise.all([
// generic async export
module.exports = new Promise(define => {
// some asynchronous operation ...
define({my:'module'});
});
// asynchronous converter.js
module.exports = module.import('./crypto')
.then((crypto) => {
// return the module to export
// modules as we know: converter.js
const crypto = require('crypto');
module.exports = {
sha256: (str, secret = '') =>
crypto.createHmac('sha256', secret)
.update(str)
.digest('hex')
};
// CommonJS old synchronous flavor
// synchronous
assert(condition, 'optional comment');
// asynchronous
assert.async(done => {
setTimeout(() => {
assert(condition, 'optional comment');
done();
});
});
// browsers don't throw on assertions failures
function assert(condition, message) {
try {
console.assert.apply(console, arguments);
// if there was a message to write
// and the assert is truthy, show such message
if (typeof message === 'string' && condition) {
console.log('✔ ' + message);
}
} catch(error) {
// in order to be able to test
// asynchronous tests too
assert.async = (fn, timeout) => {
// create a timer that will fail
const timer = setTimeout(
() => assert(false, 'timeout ' + fn),
// define a timeout or a default one
timeout || assert.timeout
);
// invoke the test function
// non exiting assert, with exitCode info
const assert = (...args) => {
try { console.assert(...args); }
catch(er) {
assert.exitCode = 1;
console.error(er);
}
};
// be sure the program know
// basic, non exiting, assert
const assert = (...args) => {
try { console.assert(...args); }
catch(er) { console.error(er); }
};
@WebReflection
WebReflection / tressa.js
Last active November 22, 2019 15:26
tressa.js in a nutshell
/*! by @WebReflection & @daw985 */
// full module, compatible with node 0.8+ & browser
// https://github.com/WebReflection/tressa
// for sync tests
function test(condition, message) {
try {
console.assert.apply(console, arguments);
if (typeof message === 'string' && condition) {