Export Cookie Jar to JSON with Node Request

The request documentation talks about importing cookies from a file in 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, he expects cookies.json already exist. The question is, if I have an exsting banner with cookies, how can I export it to JSON?

+5
source share
1 answer

I'm not sure I understand what you mean by “if I have an exsting banner with cookies in it,” but here's how I manage persistent cookies with nodejs.

To avoid errors with FileCookieStore , I add a piece of code to create a json file if it does not exist. A file may be empty if it exists:

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

Now, if you look closely at the FileCookieStore code, you will see that it calls the saveToFile method at any time when there are changes in cookies. This means that by passing the FileCookieStore object to the request module (using the jar parameter as the documentation for the request ), 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 over, simply delete the cookipath file.

Hope this helps.

+7
source

Source: https://habr.com/ru/post/1241683/


All Articles