pref.js 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. /**
  2. * @author oldj
  3. * @blog http://oldj.net
  4. */
  5. 'use strict';
  6. const fs = require('fs');
  7. const paths = require('./paths');
  8. const util = require('./util');
  9. const io = require('./io');
  10. // const AutoLaunch = require('auto-launch');
  11. // const auto_launch = new AutoLaunch({
  12. // name: 'SwitchHosts!',
  13. // path: paths.current_app_path,
  14. // });
  15. let is_loaded;
  16. let data = {};
  17. let _t;
  18. function load() {
  19. if (io.isFile(paths.preference_path)) {
  20. let cnt = fs.readFileSync(paths.preference_path, 'utf-8');
  21. try {
  22. data = JSON.parse(cnt);
  23. } catch (e) {
  24. console.log(e);
  25. }
  26. }
  27. return data;
  28. }
  29. function get(key, default_value=null) {
  30. if (!is_loaded) load();
  31. return key in data ? data[key] : default_value;
  32. }
  33. function set(key, value, callback) {
  34. clearTimeout(_t);
  35. if (!is_loaded) load();
  36. data[key] = value;
  37. _t = setTimeout(() => {
  38. fs.writeFile(paths.preference_path, JSON.stringify(data), 'utf-8', (err) => {
  39. if (err) {
  40. console.log(err);
  41. }
  42. typeof callback === 'function' && callback(err);
  43. });
  44. }, 100);
  45. }
  46. module.exports = {
  47. load: load,
  48. get: get,
  49. set: set
  50. };