1.包的地址和作用简介

:https://github.com/yeoman/configstore

用途:
轻松加载和持久化配置,而无需考虑位置和方式。(Easily load and persist config without having to think about where and how)

通过这个用途的描述,推测其为一个本地存储的配置文件。那么他存了什么东西,又是怎么存/取的呢。。

2.包的用法

  1. import Configstore from 'configstore';
  2. const packageJson = JSON.parse(fs.readFileSync('./package.json', 'utf8'));
  3. // 创建一个Configstore 实例.并初始化
  4. const config = new Configstore(packageJson.name, {foo: 'bar'});
  5. // 查
  6. console.log(config.get('foo'));
  7. //=> 'bar'
  8. // 改
  9. config.set('awesome', true);
  10. console.log(config.get('awesome'));
  11. //=> true
  12. // Use dot-notation to access nested properties.
  13. config.set('bar.baz', true);
  14. console.log(config.get('bar'));
  15. //=> {baz: true}
  16. // 删
  17. config.delete('awesome');
  18. console.log(config.get('awesome'));
  19. //=> undefined
  20. // 全部存储内容
  21. config.all
  22. // { foo: 'bar', bar: { baz: true } }

猜测一下。前面的package.json的引入貌似不关键,因为既没有改该文件,又没有和本文件有实质性的关联。勉强可以作为通过该package.json的name字段,在本地存了一个有点关联的“json”吧。

3.源码分析

3.1.引用包

  1. import path from 'path';
  2. import os from 'os';
  3. import fs from 'graceful-fs';
  4. import { xdgConfig } from 'xdg-basedir';
  5. import writeFileAtomic from 'write-file-atomic';
  6. import dotProp from 'dot-prop';
  7. 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路径进行此操作。

举例:

  1. console.log(".... " + "\n",
  2. xdgData + "\n", // 用户特定数据文件的目录
  3. xdgConfig + "\n", // 用户特定配置文件的目录
  4. xdgState + "\n", // 用户特定状态文件的目录
  5. xdgCache + "\n", // 用户特定非必要数据文件的目录
  6. xdgRuntime + "\n", // 用户特定的非基本运行时文件和其他文件对象(如套接字、命名管道等)的目录
  7. xdgDataDirectories + "\n", // 除xdgData外,用于搜索数据文件的基本目录的首选项排序数组。
  8. xdgConfigDirectories + "\n" // 除xdgConfig外,用于搜索配置文件的基本目录的首选项排序数组。
  9. );
  10. // /Users/xqs/.local/share
  11. // /Users/xqs/.config
  12. // /Users/xqs/.local/state
  13. // /Users/xqs/.cache
  14. // undefined
  15. // /Users/xqs/.local/share,/usr/local/share/,/usr/share/
  16. // /Users/xqs/.config,/etc/xdg

3.1.2. env-paths

获取存储数据、配置、缓存等内容的路径。是使用正确的操作系统特定路径。
举例:

  1. const paths = envPaths('MyApp');
  2. paths.data;
  3. paths.config;
  4. // envPaths:: /Users/xqs/Library/Preferences/myApp-nodejs
  5. // envPaths:: /Users/xqs/Library/Application Support/myApp-nodejs

3.1.3. dotProp

使用点路径从嵌套对象获取、设置或删除特性
举例:

  1. const dotProp = require('dot-prop');
  2. // Getter
  3. dotProp.get({foo: {bar: 'unicorn'}}, 'foo.bar');
  4. //=> 'unicorn'
  5. // Setter
  6. const object = {foo: {bar: 'a'}};
  7. dotProp.set(object, 'foo.bar', 'b');
  8. console.log(object);
  9. //=> {foo: {bar: 'b'}}
  10. // Has
  11. dotProp.has({foo: {bar: 'unicorn'}}, 'foo.bar');
  12. //=> true
  13. // Deleter
  14. const object = {foo: {bar: 'a'}};
  15. dotProp.delete(object, 'foo.bar');
  16. console.log(object);
  17. //=> {foo: {}}
  18. object.foo.bar = {x: 'y', y: 'x'};
  19. dotProp.delete(object, 'foo.bar.x');
  20. console.log(object);
  21. //=> {foo: {bar: {y: 'x'}}}

3.2. 功能和实现

3.2.1. 源码结构。增删改查非常清晰。重点分析一下文件的初始化和读写吧

  1. export default class Configstore {
  2. constructor(id, defaults, options = {}) {
  3. //
  4. }
  5. get all() {
  6. //
  7. }
  8. set all(value) {
  9. //
  10. }
  11. get size() {
  12. //
  13. }
  14. get(key) {
  15. //
  16. }
  17. set(key, value) {
  18. //
  19. }
  20. has(key) {
  21. //
  22. }
  23. delete(key) {
  24. //
  25. }
  26. clear() {
  27. //
  28. }
  29. get path() {
  30. //
  31. }
  32. }

3.2.1.构造器

  1. import uniqueString from 'unique-string';
  2. import { xdgConfig } from 'xdg-basedir';
  3. const configDirectory = xdgConfig || path.join(os.tmpdir(), uniqueString());
  4. constructor(id, defaults, options = {}) {
  5. // 路径前缀
  6. const pathPrefix = options.globalConfigPath ?
  7. path.join(id, 'config.json') :
  8. path.join('configstore', `${id}.json`);
  9. this._path = options.configPath || path.join(configDirectory, pathPrefix);
  10. if (defaults) {
  11. this.all = {
  12. ...defaults,
  13. ...this.all
  14. };
  15. }
  16. }

_path的初始化。支持用户自定义options.configPath。或者拼接xdgConfig得到path。那么,如果xdgConfig可以取到,就任何地方用同样的name初始化configstore都会获取到同一个path,这么操作其实不太好。

3.2.2 set all

  1. set all(value) {
  2. try {
  3. // Make sure the folder exists as it could have been deleted in the meantime
  4. fs.mkdirSync(path.dirname(this._path), mkdirOptions);
  5. writeFileAtomic.sync(this._path, JSON.stringify(value, undefined, '\t'), writeFileOptions);
  6. } catch (error) {
  7. // Improve the message of permission errors
  8. if (error.code === 'EACCES') {
  9. error.message = `${error.message}\n${permissionError}\n`;
  10. }
  11. throw error;
  12. }
  13. }

存储json时,在写入前,先创建了存储的路径。将json数据stringify后存入。

3.2.3 get all

  1. get all() {
  2. try {
  3. return JSON.parse(fs.readFileSync(this._path, 'utf8'));
  4. } catch (error) {
  5. // Create directory if it doesn't exist
  6. if (error.code === 'ENOENT') {
  7. return {};
  8. }
  9. // Improve the message of permission errors
  10. if (error.code === 'EACCES') {
  11. error.message = `${error.message}\n${permissionError}\n`;
  12. }
  13. // Empty the file if it encounters invalid JSON
  14. if (error.name === 'SyntaxError') {
  15. writeFileAtomic.sync(this._path, '', writeFileOptions);
  16. return {};
  17. }
  18. throw error;
  19. }
  20. }

将从path位置的代码取出来。这里比较值得借鉴的是错误的处理,如果是我可能就是if() else if() ,而这里是每一种情况一个if,算是一种开闭原则的应用吧。

4.总结

回答一下刚开始读时的几个疑问。
0.存的是什么,
一个json数据,存在一个静态文件里。
1.怎么读/存。
根据用户特定{配置}文件的目录,存放自己的数据。取的时候会自动从该路径下找到文件内容,取到相应的字段。
2.文件确保唯一性了吗,
没有,如果使用相同的name去初始化,那么在别处就可以取到它。
3.如何用好它,
这个,这个,这个,,,,,估计本地性的一个配置文件吧,服务器本地配置。。
4.启发
源码,不难读。这个源码真的给人提振了信心:源码不难读,成长不难做。加油,共勉