{"id":19571673,"url":"https://github.com/yued-fe/yux-storage","last_synced_at":"2025-10-11T04:02:34.045Z","repository":{"id":37631244,"uuid":"311566568","full_name":"yued-fe/yux-storage","owner":"yued-fe","description":"yux-storage 是一个基于 HTML5 IndexedDB 封装的 Web 本地数据离线存储库","archived":false,"fork":false,"pushed_at":"2023-12-15T14:47:43.000Z","size":56,"stargazers_count":156,"open_issues_count":6,"forks_count":19,"subscribers_count":7,"default_branch":"main","last_synced_at":"2024-04-25T23:04:11.064Z","etag":null,"topics":["indexeddb","localstorage-api","promise","yux-storage"],"latest_commit_sha":null,"homepage":"https://jsbin.com/bigamer/edit?console,output","language":"HTML","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/yued-fe.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null}},"created_at":"2020-11-10T06:28:17.000Z","updated_at":"2024-04-02T17:09:10.000Z","dependencies_parsed_at":"2022-08-18T03:05:35.122Z","dependency_job_id":"4d5c4d94-82bd-47cd-adfd-eb9f98432dde","html_url":"https://github.com/yued-fe/yux-storage","commit_stats":{"total_commits":25,"total_committers":2,"mean_commits":12.5,"dds":0.48,"last_synced_commit":"5e4ca849058d0d3fe4e332d49d729146f2fc9126"},"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/yued-fe%2Fyux-storage","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/yued-fe%2Fyux-storage/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/yued-fe%2Fyux-storage/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/yued-fe%2Fyux-storage/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/yued-fe","download_url":"https://codeload.github.com/yued-fe/yux-storage/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":240840036,"owners_count":19866164,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["indexeddb","localstorage-api","promise","yux-storage"],"created_at":"2024-11-11T06:19:43.524Z","updated_at":"2025-10-11T04:02:29.004Z","avatar_url":"https://github.com/yued-fe.png","language":"HTML","funding_links":[],"categories":["HTML"],"sub_categories":[],"readme":"# yux-storage\n\nyux-storage 是一个基于 HTML5 [IndexedDB](https://developer.mozilla.org/zh-CN/docs/Web/API/IndexedDB_API) 封装的 Web 本地数据离线存储库。\n\n## 特点\n\n1. 使用类似 [localStorage API](https://developer.mozilla.org/zh-CN/docs/Web/API/Window/localStorage)， 无需考虑 IndexedDB 的复杂概念，上手无压力。\n1. 支持回调和 [Promise](https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Promise) 两种方式，各凭所愿。\n1. 无任何依赖，非常轻量，100 行左右的源码，压缩后更小。\n\n以下是继承 IndexedDB 的特点\n\n1. 可以存储多种类型的数据，而不仅仅是字符串，无需序列化处理。\n1. 储存空间大，一般来说不少于 250MB，甚至没有上限。\n1. 异步操作，在进行大量数据存取时不会阻塞应用程序。\n\n## 适用场景\n\n适用于复杂对象、经常需要序列化处理的数据操作，否则使用 localStorage 更加方便\n\n## 快速开始\n\n### 安装\n\n1. 直接在 [github](https://github.com/yued-fe/yux-storage) 获取 yux-storage.js\n\n```html\n\u003cscript type=\"module\" src=\"yux-storage.js\"\u003e\u003c/script\u003e\n```\n\n\u003e 注意，`script`标签需要添加`type=\"module\"`属性\n\n2. 直接使用 unpkg [在线链接](https://unpkg.com/yux-storage)\n\n```html\n\u003cscript type=\"module\" src=\"https://unpkg.com/yux-storage\"\u003e\u003c/script\u003e\n```\n\n3. 通过 [npm](https://www.npmjs.com/package/yux-storage) 安装\n\n```cmd\nnpm i yux-storage\n```\n\n### 使用\n\n通过 script 引用，会得到一个全局变量 `yuxStorage`\n\n通过 npm 安装，需要 import 导入\n\n```js\nimport yuxStorage from 'yux-storage';\n```\n\n现在浏览器也可以通过这种方式引入\n\n```html\n\u003cscript type=\"module\"\u003e\n    import yuxStorage from './yux-storage.js'\n\u003c/script\u003e\n```\n\n在页面中使用\n\n```js\n// 回调函数\nyuxStorage.getItem('key',function(err,value){\n    if (err) {\n        console.log('出错了')\n        // 类似于 nodejs 回调格式\n    } else {\n        console.log(value)\n    }\n})\n\n// 同样支持promise\nyuxStorage.setItem('key').then(doSomethingElse)\n\n// 如果你的环境支持async，那么\nconst value = await yuxStorage.getItem('key')\nconsole.log(value)\n\n// 如果你想监听数据的更新，那么\nyuxStorage.addEventListener((type, data) =\u003e {\n    console.log(type, data)\n    // ‘setItem’, '{key, value}'\n})\n```\n\n## 测试用例\n\n可访问 [yux-storage测试用例](https://jsbin.com/bigamer/edit?console,output)，建议打开控制台哦（记得打开右上角Auto-run JS）~\n\n另外可访问[这里](https://yued-fe.github.io/yux-storage/)，需要打开控制台查看\n\n## 错误处理\n\n一般情况下报错都是参数不合法导致，例如设置添加一个键为`Object`的操作\n\n```js\nDOMException: Failed to execute 'get' on 'IDBObjectStore': The parameter is not a valid key.\n```\n\n\u003e 以下 err 为错误信息\n\n1. 回调函数直接通过第一个参数判断\n\n```js\n// 回调函数\nyuxStorage.getItem('key',function(err,value){\n    if (err) {\n        console.log('出错了',err)\n    } else {\n        console.log(value)\n    }\n})\n```\n\n2. promsie 可以通过catch来捕获\n\n```js\nyuxStorage.getItem('key').then(function(key) {\n    console.log(key);\n}).catch(err =\u003e {\n    console.log('出错了',err)\n})\n```\n\n3. async/await 可以通过 try...catch 来捕获\n\n```js\ntry {\n    const  key = await yuxStorage.getItem('key');\n} catch (error) {\n    console.log('出错了',err)\n}\n```\n\n## 多数据库\n\n默认情况下会创建名为`yux-project`的数据库，如果有多数据库需求，可以通过`YuxDB`自行创建\n\n```js\nimport { YuxDB } from 'yuxStorage'\nconst MyStorage = new YuxDB('test')\n```\n\n\u003e 在多账号下本地储存比较有用\n\n## API\n\n获取或设置离线仓库中的数据的 API。风格参考 [localStorage API](https://developer.mozilla.org/zh-CN/docs/Web/API/Window/localStorage)\n\n### **GETITEM**\n\n```js\nyuxStorage.getItem(key, callback)\n```\n\n从仓库中获取 key 对应的值并将结果提供给回调函数。如果 `key` 不存在，`getItem()` 将返回 `undefined`。\n\n\u003e 所有回调函数的第一个参数为**错误信息**，如果为 `false`，说明设置正常\n\n*示例*\n\n```js\nyuxStorage.getItem('somekey').then(function(value) {\n    // 当离线仓库中的值被载入时，此处代码运行\n    console.log(value);\n})\n\n// async版本:\nconst value = await yuxStorage.getItem('somekey');\n// 当离线仓库中的值被载入时，此处代码运行\nconsole.log(value);\n\n// 回调版本:\nyuxStorage.getItem('somekey', function(err,value) {\n    // 当离线仓库中的值被载入时，此处代码运行\n    console.log(err, value);\n});\n\n```\n\n### **SETITEM**\n\n```js\nyuxStorage.setItem(key, value, callback)\n```\n\n将数据保存到离线仓库。你可以存储如下类型的 JavaScript 对象：\n\n* Array\n* ArrayBuffer\n* Blob\n* Float32Array\n* Float64Array\n* Int8Array\n* Int16Array\n* Int32Array\n* Number\n* Object\n* Uint8Array\n* Uint8ClampedArray\n* Uint16Array\n* Uint32Array\n* String\n\n\u003e 可能不太完整，理论上支持任意格式的数据，不能是 function\n\n*示例*\n\n```js\nyuxStorage.setItem('somekey', 'some value').then(function (value) {\n    // 当值被存储后，可执行其他操作\n    console.log(value);\n})\n\n// 不同于 localStorage，你可以存储非字符串类型（强烈推荐，无需序列化处理）\nyuxStorage.setItem('my array', [1, 2, 'three']).then(function(value) {\n    // 如下输出 `1`\n    console.log(value[0]);\n})\n\n// 键名也可以是数组或者数字（不推荐，一般用字符串就足够了）\nyuxStorage.setItem([1,2,3], [1, 2, 'three'])\n\n// 还可以存储 file 文件\n\nconst file = new File([\"foo\"], \"foo.txt\", {\n    type: \"text/plain\",\n});\n\nyuxStorage.setItem('file', file)\n\n// 报错，不能是function\nyuxStorage.setItem('file', function(){})\n```\n\n### **REMOVEITEM**\n\n```js\nyuxStorage.removeItem(key, callback)\n```\n\n从离线仓库中删除 key 对应的值。\n\n*示例*\n\n```js\nyuxStorage.removeItem('somekey').then(function() {\n    // 当值被移除后，此处代码运行\n    console.log('Key is cleared!');\n})\n```\n\n### **CLEAR**\n\n```js\nyuxStorage.clear(callback)\n```\n\n从数据库中删除所有的 key，重置数据库。\n\n\u003e !小心使用，会删除所有数据\n\n*示例*\n\n```js\nyuxStorage.clear().then(function() {\n    // 当数据库被全部删除后，此处代码运行\n    console.log('Database is now empty.');\n})\n```\n\n### **KEY**\n\n```js\nyuxStorage.key(keyIndex, callback)\n```\n\n根据 key 的索引获取其名，如果不存在返回 `undefined`\n\n\u003e  有些鸡肋的方法，很多时候我们不知道键的索引。\n\n*示例*\n\n```js\nyuxStorage.key(2).then(function(keyName) {\n    // key 名\n    console.log(keyName);\n})\n```\n\n### **KEYS**\n\n```js\nyuxStorage.keys(callback)\n```\n\n获取数据仓库中所有的 key，如果不存在返回空数组`[]`。\n\n\u003e  localStorage API 并没有这个方法，但比上面的 key 要有用的多。\n\n*示例*\n\n```js\nyuxStorage.keys().then(function(keyNames) {\n    // 所有的key名\n    console.log(keyNames);\n})\n```\n\n## 监听器\n\n如果想监听数据的更新，可以使用`addEventListener`方法，`setItem`、`removeItem`、`clear` 都会触发回调\n\n```js\nyuxStorage.addEventListener((type, data, projectName) =\u003e {\n    console.log(type, data, projectName)\n    // ‘setItem’, '{key, value}', 'yux-project'\n})\n```\n\n同时也支持全局调用，可以通过监听 `document` 自定义事件\n\n```js\ndocument.addEventListener('yuxStorage', ev =\u003e {\n    // 自定义事件的数据在 ev.detail\n    const [type, data, projectName] = ev.detail;\n    console.log(type, data, projectName)\n    // ‘setItem’, '{key, value}', 'yux-project'\n})\n```\n\n\u003e 支持多次调用\n\n## 兼容性\n\n现代浏览器，包括移动端，不支持 `IE`\n\n\u003e 兼容性取决于 [indexedDB](https://caniuse.com/?search=indexedDB) 和 [Promise](https://caniuse.com/?search=Promise)\n\n\n## 联系我\n\n有相关问题或者意见可与我联系 yanwenbin1991@live.com\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fyued-fe%2Fyux-storage","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fyued-fe%2Fyux-storage","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fyued-fe%2Fyux-storage/lists"}