var https = require("https");
var fs = require("fs");
function request(url) {
return new Promise((resolve, reject) => {
var options = {
method: "GET",
hostname: "www.jianshu.com",
path: url,
headers: {
Cookie: "remember_user_token=" + token + "; locale=zh-CN",
Referer: "https://www.jianshu.com/writer",
Accept: "application/json",
},
};
var req = https.request(options, function (res) {
var chunks = [];
var size = 0;
res.on("data", function (chunk) {
chunks.push(chunk);
size += chunk.length;
});
res.on("end", function (chunk) {
var body = Buffer.concat(chunks, size);
// let res = iconv.decode(body, 'utf-8');
var res = body.toString("utf-8");
resolve(JSON.parse(res));
});
res.on("error", reject);
});
req.end();
});
}
function createFile(path, data) {
const root = `./jianshu`;
try {
if (!path) {
// 根目录
fs.mkdirSync(root);
} else if (path.name) {
// 目录
fs.mkdirSync(`${root}/${path.name}`);
} else if (path.notebook_id) {
// 文章
const filepath = `${root}/${dic_dir[path.notebook_id]}/${path.title}.md`;
fs.writeFileSync(filepath, data);
}
} catch (e) {
console.log(e.message);
}
}
// 登录后拿到名为 remember_user_token 的 cookie
const token = "W1sxMDA3MDI5N10sIiQyYSQxMSRjQ2k2cVhhVTAyek1DTFBMZnNIL1UuIiwiMTYyMTgyNDk2My4zNjQ0Njg4Il0%3D--4bc3f3749267abd427a0be03b084c9e9d6ad45e8";
let dic_dir = {};
createFile();
request("/author/notebooks")
.then((res) => {
return Promise.all(
Array.from(res).map((item) => {
createFile(item);
dic_dir[item.id] = item.name;
return request(`/author/notebooks/${item.id}/notes`);
})
);
})
.then((res) => {
let dirs = [];
Array.from(res).forEach((item) => dirs.push(...item));
dirs.forEach((item) => {
request(`/author/notes/${item.id}/content`)
.then((file) => createFile(item, file.content))
.catch((e) => console.error(e));
});
})
.catch((e) => console.error(e));
网友评论