javascript - I'm running into some trouble storing a key-value object in a log file -
var filehasher = require("./filehasher"); if (process.argv.length < 3) { console.log("program file , 1 argument required program."); process.exit(1); } var filename = process.argv[2]; var fs = require('fs'); var file = fs.readfilesync(filename, "utf-8"); // file contents var data = fs.readfilesync("../sha1.txt", "utf-8"); // read current key-value pairs console.log(data); // print current key-value pairs var filesha1 = filehasher(file); console.log(filesha1); var object = { name: filename, value: filesha1 }; console.log(object); fs.appendfile("../sha1.txt", json.stringify(object), function(err) { console.log(err); console.log(object); // prints object know stored correctly }); right works fine. however, when saving object text file, instead of getting format:
{ "name":"sha1.js", "value":"6d358b6f267e22e327c1028e79a5c8b200bf453d" }; i this:
{"name":"sha1.js","value":"6d358b6f267e22e327c1028e79a5c8b200bf453d"} i want change spacing , add semicolon when object saved. in future plan on parsing list check whether or not file exists, , change value of value upon update in sha1 of file. guiding hand towards right way format code or object, or perhaps different function should using, appreciated!
those 2 things identical, when parsed, ignoring semicolon. semicolons not valid after json objects, should have between records (a comma more appropriate, if anything).
now, the json.stringify function has few little-known parameters controlling whitespace , other pretty-print features. looks want js-standard two-space indentation, call json.stringify(object, null, ' ').
to add semicolon -- shouldn't -- can use string concatenation:
fs.appendfile("../sha1.txt", json.stringify(object) + ';\n', function(err) { this add semicolon , newline after json string. since semicolon added after serialization, occur @ end of message regardless of line count.
Comments
Post a Comment