Skip to content

Instantly share code, notes, and snippets.

@jkeyes
Created December 5, 2011 22:43
Show Gist options
  • Save jkeyes/1435747 to your computer and use it in GitHub Desktop.
Save jkeyes/1435747 to your computer and use it in GitHub Desktop.
/*** tough-cookie/lib/cookie.js ***/
/* I added the following to the end of the file for testing purposes */
memstore = require('./memstore');
module.exports.memorystore = memstore.MemoryCookieStore;
/*** jsonstore.js ***/
var tough = require('tough-cookie');
// ...
function JSONFileCookieStore(filename) {
this.filename = filename != null ? filename : ".tcjar";
this.memorystore = new tough.memorystore()
}
// ...
JSONFileCookieStore.prototype.findCookie = function findCookie(domain, path, key, cb) {
var cookiestore = this;
this._read_store(function(err) {
if (err) {
cb(err);
return;
}
return cookiestore.memorystore.findCookie(domain, path, key, cb);
});
};
// ...
JSONFileCookieStore.prototype.putCookie = function putCookie(cookie, cb) {
this.memorystore.putCookie(cookie, cb);
this._write_store(function(err) {
cb(err);
});
};
// ...
JSONFileCookieStore.prototype._read_store = function(cb) {
// load cookies
var cookiestore = this;
fs.readFile(this.filename, "utf-8", function(err, data) {
if (err) {
cb(err);
return;
}
json_cookies = data.split("\n");
console.log(json_cookies);
for (var i = 0; i < json_cookies.length; i++) {
if (json_cookies[i] == '') continue;
cookiestore.memorystore.putCookie(tough.fromJSON(json_cookies[i]), function() {});
}
cb(null);
});
}
JSONFileCookieStore.prototype._write_store = function(cb) {
var json_cookies = [];
var store = this.memorystore;
for (domain in store.idx) {
for (path in store.idx[domain]) {
for (key in store.idx[domain][path]) {
json_cookies.push(JSON.stringify(store.idx[domain][path][key]));
}
}
}
try {
fs.writeFile(this.filename, json_cookies.join("\n"), "utf-8");
cb(null);
} catch (err) {
cb(err);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment