npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

browser-ls

v1.4.0

Published

Tiny wrapper for localStorage (DOM Storage) that handles exceptions via callbacks

Downloads

9

Readme

browser-ls

build-status version

browser-ls provides a nice node-like wrapper on the localStorage API in browsers. It handles potential localStorage exceptions for you, plus it's only 3KB minified!

It handles exceptions internally via try catch blocks and will return errors in the Node.js fashion of using the first callback parameter as an error argument. This means it'll play nicely with other Node.js modules that are supported in the browser like Async.js.

Install

Via NPM:

npm i browser-ls

Via Bower

bower i browser-ls

You can also just drop a file from the dist/ folder here into your project.

Example

var ls = require('browser-ls');

// If you're not Browserify-ing you can use:
// var ls = window.ls ;
// instead of "require"

ls.setJson('somejson', {
	name: 'Bruce Wayne',
	aka: 'Batman'
}, function (err) {
	if (err) {
		alert('Failed to write to localStorage');
	} else {
		ls.getJson('somejson', function(err, json) {
			if (err) {
				alert('Failed to get item from localStorage')
			} else {
				alert('We stored and retrieved JSON from localStorage!');
				alert('Result: ' + JSON.stringify(json));
			}
		});
	}
});

Because this module uses a standard Node callback pattern if you like neater code the above could be written like so:

var async = require('async'),
	ls = require('browser-ls');

var STORAGE_KEY = 'somejson'

async.series({
	writeToLs: function (cb) {
		ls.setJson(STORAGE_KEY, {
			name: 'Bruce Wayne',
			aka: 'Batman'
		}, cb);
	}, 
	readFromLs: function (cb) {
		ls.getJson(STORAGE_KEY, cb);
	}
}, function (err, res) {
	if (err) {
		alert('Something went wrong...');
	} else {
		alert('We stored and retrieved JSON from localStorage!');
		alert('Result: ' + JSON.stringify(res.readFromLs));
	}
})

Browser Support

I've tested this on the following browsers but it should work on pretty much any browser with JSON and localStorage support.

  • Safari 7.0.5
  • Chrome 37.0.2062
  • Firefox 29.0.0

If the awesome ci.testling service has the timeout issues it's recently experiencing resolved a more complete browser support matrix can be constructed then.

API

All callbacks receive an error as the first parameter which will be null if no error occured. All methods that retreive an item take a second parameter that is the result.

get(key, callback)

Get a string value from localStorage.


var ls = require('browser-ls');

ls.get('SOME_KEY', function (err, result) {
	if (err) {
		// DARN!
	} else {
		// WOO-HOO!
	}
});

getJson(key, callback)

Get an Object from localStorage.

set(key, string[, callback])

Set a string value in localStorage.

setJson(key, object[, callback])

Write a JSON object to localStorage.

remove(key[, callback])

Remove an object from localStorage.

getAdapter (name)

This will get a localStorage interface that stores data under the given key name to avoid clashes. It has all the standard API methods.

For example:


var ls = require('browser-ls');

var Users = ls.getAdapter('Users');

Users.set('KEY', 'some value');
ls.set('KEY', 'another value');

Users.get('KEY', function (err, res) {
	// res will equal 'some value'
});
ls.get('KEY' function (err, res) {
	// res will equal 'another value'
});

Using a single instance to do this would have overwritten the Users value with that of the plain ls interface.

getAdapter also has more advanced usage and supports pre-save and post-load transforms. These are useful if you need to store encrypted data or performs modification of data prior to saving. Here's an example"

var ls = require('browser-ls');
var encryption = require('./encryption');
var userId = 'user-1234';

var Users = ls.getAdapter({
	ns: 'Users', // Store data under this namespace
	preSave: doEncrypt,
	postLoad: doDecrypt
});

function doEncrypt (val, callback) {
	// val is the value passed to the .set method below
	encryption.encrypt(val, function (err, encryptedVal) {
		if (err) {
			callback(err, null);
		} else {
			// Send the updated value to the callback to be saved
			callback(null, encryptedVal)
		}
	});
}

function doEncrypt (val, callback) {
	// val is the value that the module got from localStorage 
	// in this case it is the encrypted value of:
	// '{"name":"evan","location":"USA"}''
	encryption.decrypt(val, function (err, decryptedVal) {
		if (err) {
			callback(err, null);
		} else {
			// Send the updated value to the callback to be loaded
			callback(null, decryptedVal)
		}
	});
}

// This JSON string being saved will be encrypted by preSave
Users.set(userId, JSON.stringify({
	name: 'evan',
	location: 'USA'
}));


// The value we get will automatically be decrpyted
Users.get(userId, function (err, user) {
	// user object will be equal to the originally saved data
});

In the above examples you could replace set and get with setJson and getJson and the encryption would still work since the pre and post functions are called directly before the safe after the JSON is stringified (set) and before it's parsed (get).

Changelog

1.4.0

Added support for pre-save and post-load transforms.

pre 1.4.0

Not documented...