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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With