1.包的地址和作用简介
:https://github.com/yeoman/configstore
用途:
轻松加载和持久化配置,而无需考虑位置和方式。(Easily load and persist config without having to think about where and how)
通过这个用途的描述,推测其为一个本地存储的配置文件。那么他存了什么东西,又是怎么存/取的呢。。
2.包的用法
import Configstore from 'configstore';const packageJson = JSON.parse(fs.readFileSync('./package.json', 'utf8'));// 创建一个Configstore 实例.并初始化const config = new Configstore(packageJson.name, {foo: 'bar'});// 查console.log(config.get('foo'));//=> 'bar'// 改config.set('awesome', true);console.log(config.get('awesome'));//=> true// Use dot-notation to access nested properties.config.set('bar.baz', true);console.log(config.get('bar'));//=> {baz: true}// 删config.delete('awesome');console.log(config.get('awesome'));//=> undefined// 全部存储内容config.all// { foo: 'bar', bar: { baz: true } }
猜测一下。前面的package.json的引入貌似不关键,因为既没有改该文件,又没有和本文件有实质性的关联。勉强可以作为通过该package.json的name字段,在本地存了一个有点关联的“json”吧。
3.源码分析
3.1.引用包
import path from 'path';import os from 'os';import fs from 'graceful-fs';import { xdgConfig } from 'xdg-basedir';import writeFileAtomic from 'write-file-atomic';import dotProp from 'dot-prop';import uniqueString from 'unique-string';
path,os,fs没什么好说的,算比较公共。writeFileAtomic,顾名思义:以原子方式写入文件,并具有可配置的所有权,不展开。unique-string返回一个32位的md5字符串。
说一下几个眼生的新包。
3.1.1 xdg-basedir vs env-paths
xdg-basedir:
用户特定{配置}文件的目录
这个软件包是针对Linux的。您不应该在macOS或Windows上使用XDG。相反,您应该遵循他们的平台约定。您可以使用env路径进行此操作。
举例:
console.log(".... " + "\n",xdgData + "\n", // 用户特定数据文件的目录xdgConfig + "\n", // 用户特定配置文件的目录xdgState + "\n", // 用户特定状态文件的目录xdgCache + "\n", // 用户特定非必要数据文件的目录xdgRuntime + "\n", // 用户特定的非基本运行时文件和其他文件对象(如套接字、命名管道等)的目录xdgDataDirectories + "\n", // 除xdgData外,用于搜索数据文件的基本目录的首选项排序数组。xdgConfigDirectories + "\n" // 除xdgConfig外,用于搜索配置文件的基本目录的首选项排序数组。);// /Users/xqs/.local/share// /Users/xqs/.config// /Users/xqs/.local/state// /Users/xqs/.cache// undefined// /Users/xqs/.local/share,/usr/local/share/,/usr/share/// /Users/xqs/.config,/etc/xdg
3.1.2. env-paths
获取存储数据、配置、缓存等内容的路径。是使用正确的操作系统特定路径。
举例:
const paths = envPaths('MyApp');paths.data;paths.config;// envPaths:: /Users/xqs/Library/Preferences/myApp-nodejs// envPaths:: /Users/xqs/Library/Application Support/myApp-nodejs
3.1.3. dotProp
使用点路径从嵌套对象获取、设置或删除特性
举例:
const dotProp = require('dot-prop');// GetterdotProp.get({foo: {bar: 'unicorn'}}, 'foo.bar');//=> 'unicorn'// Setterconst object = {foo: {bar: 'a'}};dotProp.set(object, 'foo.bar', 'b');console.log(object);//=> {foo: {bar: 'b'}}// HasdotProp.has({foo: {bar: 'unicorn'}}, 'foo.bar');//=> true// Deleterconst object = {foo: {bar: 'a'}};dotProp.delete(object, 'foo.bar');console.log(object);//=> {foo: {}}object.foo.bar = {x: 'y', y: 'x'};dotProp.delete(object, 'foo.bar.x');console.log(object);//=> {foo: {bar: {y: 'x'}}}
3.2. 功能和实现
3.2.1. 源码结构。增删改查非常清晰。重点分析一下文件的初始化和读写吧
export default class Configstore {constructor(id, defaults, options = {}) {//}get all() {//}set all(value) {//}get size() {//}get(key) {//}set(key, value) {//}has(key) {//}delete(key) {//}clear() {//}get path() {//}}
3.2.1.构造器
import uniqueString from 'unique-string';import { xdgConfig } from 'xdg-basedir';const configDirectory = xdgConfig || path.join(os.tmpdir(), uniqueString());constructor(id, defaults, options = {}) {// 路径前缀const pathPrefix = options.globalConfigPath ?path.join(id, 'config.json') :path.join('configstore', `${id}.json`);this._path = options.configPath || path.join(configDirectory, pathPrefix);if (defaults) {this.all = {...defaults,...this.all};}}
_path的初始化。支持用户自定义options.configPath。或者拼接xdgConfig得到path。那么,如果xdgConfig可以取到,就任何地方用同样的name初始化configstore都会获取到同一个path,这么操作其实不太好。
3.2.2 set all
set all(value) {try {// Make sure the folder exists as it could have been deleted in the meantimefs.mkdirSync(path.dirname(this._path), mkdirOptions);writeFileAtomic.sync(this._path, JSON.stringify(value, undefined, '\t'), writeFileOptions);} catch (error) {// Improve the message of permission errorsif (error.code === 'EACCES') {error.message = `${error.message}\n${permissionError}\n`;}throw error;}}
存储json时,在写入前,先创建了存储的路径。将json数据stringify后存入。
3.2.3 get all
get all() {try {return JSON.parse(fs.readFileSync(this._path, 'utf8'));} catch (error) {// Create directory if it doesn't existif (error.code === 'ENOENT') {return {};}// Improve the message of permission errorsif (error.code === 'EACCES') {error.message = `${error.message}\n${permissionError}\n`;}// Empty the file if it encounters invalid JSONif (error.name === 'SyntaxError') {writeFileAtomic.sync(this._path, '', writeFileOptions);return {};}throw error;}}
将从path位置的代码取出来。这里比较值得借鉴的是错误的处理,如果是我可能就是if() else if() ,而这里是每一种情况一个if,算是一种开闭原则的应用吧。
4.总结
回答一下刚开始读时的几个疑问。
0.存的是什么,
一个json数据,存在一个静态文件里。
1.怎么读/存。
根据用户特定{配置}文件的目录,存放自己的数据。取的时候会自动从该路径下找到文件内容,取到相应的字段。
2.文件确保唯一性了吗,
没有,如果使用相同的name去初始化,那么在别处就可以取到它。
3.如何用好它,
这个,这个,这个,,,,,估计本地性的一个配置文件吧,服务器本地配置。。
4.启发
源码,不难读。这个源码真的给人提振了信心:源码不难读,成长不难做。加油,共勉
