使用Node Request将Cookie Jar导出到JSON [英] Export Cookie Jar to JSON with Node Request

查看:165
本文介绍了使用Node Request将Cookie Jar导出到JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请求文档使用以下示例讨论有关从文件导入cookie的操作:

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

但是,如评论中所述,它预计 cookies.json 已经存在。问题是,如果我有一个装有饼干的罐子,如何将其导出到JSON?

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.

为避免 FileCookieStore 的错误,我在其中添加了一段代码如果不存在,请创建json文件。只要存在,该文件就可以为空:

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

现在,如果您仔细查看 FileCookieStore 代码,只要Cookie发生更改,您就会看到它调用 saveToFile 方法。这意味着通过将 FileCookieStore 对象传递给 request 模块(使用 jar 选项作为请求文档解释),json文件将始终反映

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.

这是一个完整的示例:

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 文件。

To start anew, simply delete the cookipath file.

这篇关于使用Node Request将Cookie Jar导出到JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆