local-storage-v8
TypeScript icon, indicating that this package has built-in type declarations

0.1.1 • Public • Published

local-storage-v8

This package is based on asyn_hooks which is added in node 8.1, make sure your node is >=8.1.

Install

npm install local-storage-v8 --save

Test

npm test

Usage

// import
import { Enable, Disable, GetStorage } from "local-storage-v8";
 
// or require
const { Enable, Disable, GetStorage } = require("local-storage-v8");

Considering local storage is mostly used in web applications,here is a simple example for koa2. The source code is here, you can also clone it from the repository.

// say.js
module.exports = function(){
    const store = require("local-storage-v8").GetStorage();
    return store.name;
}
// server.js
const Koa = require("koa");
const app = new Koa();
const { GetStorage } = require("local-storage-v8");
const say = require("./say");
const asyncHooks = require("async_hooks");
 
const delay = seconds =>
    new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve();
        }, seconds * 1000);
    });
 
app
    .use(async (ctx, next) => {
        let store = GetStorage();
        store.name = ctx.query.name;
        await delay(Math.random() * 10 | 0);
        next();
    })
    .use((ctx, next) => {
        ctx.body = `hello, ${say()}.`;// you see, no need for ctx or req here.
    });
 
app.listen(9922);
 
// client.js
let rp = require("request-promise");
 
(function(){
    for(let k = 0; k < 10; k++){
        rp.get(`http://127.0.0.1:9922?name=${k}th`).then(data => {
            if(data !== `hello, ${k}th.`){
                throw new Error("Check failed!");
            } else {
                console.log(`${k}th done.`);
            }
        });
    }
})();

Dependency

The source code, which is written in Typescript, is less than 40 lines, and no extra package needed. This package is highly inspired by another similar package called async-local-storage in npmjs, where we need modify or get the value through set or get. Feel free to modify the source code.

Readme

Keywords

none

Package Sidebar

Install

npm i local-storage-v8

Weekly Downloads

0

Version

0.1.1

License

none

Last publish

Collaborators

  • shanyy