require-utils.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. 'use strict';
  2. var fs = require('fs');
  3. function safeRequire (path) {
  4. var resolved;
  5. try {
  6. resolved = require(path);
  7. } catch (e) {
  8. console.error("Could not require: " + path, e);
  9. }
  10. return resolved;
  11. }
  12. function safeLoadFile(path) {
  13. var resolved;
  14. try {
  15. resolved = JSON.parse(fs.readFileSync(path, 'utf8'));
  16. //console.log('content = ' , resolved);
  17. } catch (e) {
  18. console.error("Could not require: " + path, e);
  19. }
  20. return resolved;
  21. }
  22. function requireWithTimestamp (path) {
  23. var resolved = safeLoadFile(path);
  24. if (resolved) {
  25. resolved.timestamp = fs.statSync(path).mtime;
  26. }
  27. return resolved;
  28. }
  29. // Functions that are needed in order to test the module. Can be removed in the future.
  30. function compareMethods(path) {
  31. var new_data = safeLoadFile(path);
  32. var old_data = safeRequire(path);
  33. if (JSON.stringify(new_data) === JSON.stringify(old_data) ) {
  34. console.log("test passed", new_data, old_data);
  35. } else {
  36. console.log("test failed");
  37. }
  38. }
  39. // Module tests.
  40. if (!module.parent) {
  41. // Write the first file: and test it.
  42. var obj = {x: "x", y: 1}
  43. fs.writeFileSync('/tmp/file1.json', JSON.stringify(obj));
  44. compareMethods('/tmp/file1.json');
  45. // Check a non existing object.
  46. compareMethods('/tmp/not_exist.json');
  47. // check a file that is not formated well.
  48. fs.writeFileSync('/tmp/bad.json', '{"x":"x","y":1');
  49. compareMethods('/tmp/bad.json');
  50. // Rewrite the file and reread it.
  51. var new_obj = {x: "x", y: 2}
  52. fs.writeFileSync('/tmp/file1.json', JSON.stringify(new_obj));
  53. var obj_read = safeLoadFile('/tmp/file1.json');
  54. if (JSON.stringify(new_obj) === JSON.stringify(obj_read) ) {
  55. console.log("test passed");
  56. } else {
  57. console.log("test failed");
  58. }
  59. }
  60. module.exports = {
  61. safeRequire: safeRequire
  62. , requireWithTimestamp: requireWithTimestamp
  63. , safeLoadFile: safeLoadFile
  64. };