joepie91 / node-bhttp

A sane HTTP client library for Node.js with Streams2 support.
62 stars 12 forks source link

save/load session to a file #36

Closed sam0x17 closed 7 years ago

sam0x17 commented 7 years ago

Is there a way to do this? I've tried various serialization libraries in an attempt to serialize a bhttp session object, however there are some native objects buried in there that prevent it from working. The reason I want to do this is I am writing a command-line utility that maintains a state between invocations (sort of like git) and I want to retain session data without having to re-login each time.

Any suggestions?

update: I figured it out -- the secret is that bhttp uses tough-cookie by default to manage cookies, and in 2015 tough-cookie added a serialization / deserialization routine that is compatible with JSON. Basically see this commit in tough-cookie: https://github.com/salesforce/tough-cookie/pull/42/files#diff-04c6e90faac2675aa89e2176d2eec7d8R337

In my case, serialization and deserialization were handled as follows:

account.saveSession = () => {
  if(account.session == null) return
  var obj = account.session._sessionOptions.cookieJar.jar.serializeSync()
  fs.writeFileSync(account.sessionPath, JSON.stringify(obj))
}

account.loadSession = () => {
  var obj = JSON.parse(fs.readFileSync(account.sessionPath, {'encoding': 'utf8'}))
  account.resetSession()
  account.session._sessionOptions.cookieJar.jar = CookieJar.deserializeSync(obj)
}
sam0x17 commented 7 years ago

note that CookieJar in the sample above is toughCookie.CookieJar