UNPKG

jooo

Version:

Write Plain Old Javascript Object to file

57 lines (44 loc) 1.45 kB
const fse = require('fs-extra'); const fs = require('fs'); const beautify = require('js-beautify').js_beautify; var toString = Object.prototype.toString; function dump_object(obj) { var buff, prop; buff = []; for (prop in obj) { buff.push(dump_to_string(prop) + ': ' + dump_to_string(obj[prop])); } return '{' + buff.join(', ') + '}'; } function dump_array(arr) { var buff, i, len; buff = []; for (i=0, len=arr.length; i<len; i++) { buff.push(dump_to_string(arr[i])); } return '[' + buff.join(', ') + ']'; } function dump_to_string(obj) { if (toString.call(obj) == '[object Function]') { return obj.toString(); } else if (toString.call(obj) == '[object Array]') { return dump_array(obj); } else if (toString.call(obj) == '[object String]') { return '"' + obj.replace('"', '\\"').replace(/\n/g, '\\n').replace(/\r/g, '\\r').replace(/\t/g, '\\t') + '"' ; } else if (obj === Object(obj)) { return dump_object(obj); } return obj.toString(); } module.exports = { write: function(path, data){ var result = dump_to_string(data); var beautified = beautify(result, { indent_size: 4 }); fse.outputFileSync(path, beautified); }, read: function(path){ const contents = fs.readFileSync(path, {encoding: 'utf8'}); const result = dump_to_string(contents); return result; } };