knobz lets you declare and manage feature flags in your JavaScript/Node.js application using JSON Predicates to declarative configure whether features should be enabled.
Install the module using npm:
npm install knobz --save
Usage example in Node.js:
const knobz = require('knobz');
knobz.configure({
features: [{
id: 'user_account_lockout',
description: 'Failed sign-in attempts will cause a user account to be locked.',
owner: 'Ismael Rivera <[email protected]>',
enabled: true
}]
});
if (knobz.isFeatureEnabled('user_account_lockout')) {
// user account should be locked
}
If you're rolling out a new feature, you might want to verify the feature as expected by slowly enabling it for a percentage of your users.
knobz.configure({
features: [{
id: 'one_click_checkout_beta',
description: 'Phased rollout of feature that allows to make online purchases with a single click.',
owner: 'Ismael Rivera <[email protected]>',
percentage: 0.2, // 20%
percentagePath: '/email'
}]
});
The algorithm for determining whether the feature is enabled for a given context is as follows:
djb2(String(valueAtPath)) % 100 < (feature.percentage * 100);
Features may be enabled only if a given context satisfies its criteria
, defined as a JSON Predicate.
The following example enables the feature to a subset of users based on their job title:
knobz.configure({
features: [{
id: 'cool_new_email_for_managers',
criteria: {
op: 'contains',
path: '/jobTitle',
value: 'Manager',
ignore_case: true
}
}]
});
Configure knobz using any of the following options:
features
: can be either an array of features or a function to load features dynamically. If a function is passed, it must return a Promise that resolves to an array of features.reloadInterval
: interval in ms used by knobz to reload features when configured with a function to load features dynamically.
Return object with all features IDs as properties, and true/false as values, indicating whether they are enabled for a given context.
Return true/false if a feature is enabled for a given context.
Force a reload by calling the configured function to load features dynamically.
knobz is also an event emitter which provides an on
method allowing your application to listen for any of the following events.
Triggers whenever the feature is checked with a given context. The listener is called with featureId
, the context
used, and the boolean enabled
indicating whether the feature is enabled.
{
enabled: <Boolean>,
featureId: <String>,
context: <Object>
}
Triggers whenever the features are reloaded. The listener is called with an object including the features array.
{
features: <Object[]>
}
Triggers whenever the function to reload features throws an error. The event handler is called with the error.
To run the test suite, first install the dependencies, then run npm test
:
npm install
npm test