Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Export Cookie Jar to JSON with Node Request

The request documentation talks about importing cookies from a file with the following example:

var FileCookieStore = require('tough-cookie-filestore');
// NOTE - currently the 'cookies.json' file must already exist!
var j = request.jar(new FileCookieStore('cookies.json'));
request = request.defaults({ jar : j })
request('http://www.google.com', function() {
  request('http://images.google.com')
})

However, as noted in the comment, it expects cookies.json to already exist. The question is, if I have an exsting jar with cookies in it, how can I export it to JSON?

like image 392
Joshua Gilman Avatar asked Jan 28 '16 04:01

Joshua Gilman


1 Answers

I am not sure to understand what you mean by "if I have an exsting jar with cookies in it", but here is how I manage persistent cookies with nodejs.

To avoid errors with FileCookieStore, I add a piece of code to create the json file if it does not exist. The file can be empty, as long as it exists:

if(!fs.existsSync(cookiepath)){
    fs.closeSync(fs.openSync(cookiepath, 'w'));
}

Now, if you look closely at the FileCookieStore code, you will see it calls the saveToFile method anytime there is a change in the cookies. It means that by passing a FileCookieStore object to the request module (using the jar option as the request documentation explains), the json file will always reflect the state of the cookies.

Here is a complete example:

var FileCookieStore = require('tough-cookie-filestore');
var request = require('request');
var fs = require("fs");

var cookiepath = "cookies.json";

// create the json file if it does not exist
if(!fs.existsSync(cookiepath)){
    fs.closeSync(fs.openSync(cookiepath, 'w'));
}

// use the FileCookieStore with the request package
var jar = request.jar(new FileCookieStore(cookiepath));
request = request.defaults({ jar : jar });

// do whatever you want
request('http://www.google.com', function() {
    request('http://images.google.com')
});

// the cookies in 'jar' corresponds to the cookies in cookies.json
console.log(jar);

To start anew, simply delete the cookipath file.

like image 143
Derlin Avatar answered Oct 27 '22 07:10

Derlin