使用节点请求将Cookie JAR导出到JSON

request文档通过以下示例介绍如何从文件导入cookie:

 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') }) 

但是,正如评论中指出的那样,它预计cookies.json已经存在。 问题是,如果我有一个带有cookie的exsting jar,我怎样才能把它导出到JSON?

我不确定明白你的意思是“如果我有一个带有cookie的exsting jar”,但这里是我如何pipe理与nodejs的持久cookie。

为了避免FileCookieStore出错,我添加了一段代码来创buildjson文件,如果它不存在。 该文件可以是空的,只要它存在:

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

现在,如果仔细查看FileCookieStore代码,您会发现每当cookie发生更改时,都会调用saveToFile方法。 这意味着通过将FileCookieStore对象传递给request模块(使用请求文档解释的jar选项),json文件将始终反映cookie的状态。

这是一个完整的例子:

 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); 

要重新开始,只需删除cookipath文件。

希望这可以帮助。