Skip to content

Instantly share code, notes, and snippets.

@dgootman
Created February 3, 2024 23:55
Show Gist options
  • Save dgootman/ccb1d4ddef5ebb667ace0496fffbcd7a to your computer and use it in GitHub Desktop.
Save dgootman/ccb1d4ddef5ebb667ace0496fffbcd7a to your computer and use it in GitHub Desktop.
Node.js HTTP client with Netscape cookie file support and auto-refresh on cookie file changes
import { watch } from "chokidar";
import FileCookieStore from "file-cookie-store";
import got, { HTTPError } from "got";
import { Cookie, CookieJar, MemoryCookieStore } from "tough-cookie";
import * as winston from "winston";
const logger = winston.createLogger({
level: "debug",
format: winston.format.combine(
winston.format.timestamp({
format: "YYYY-MM-DD HH:mm:ss",
}),
winston.format.errors({ stack: true }),
winston.format.splat(),
winston.format.json(),
winston.format.colorize({ all: true })
),
transports: [new winston.transports.File({ filename: "/dev/stderr" })],
});
class RefreshingFileCookieStore extends MemoryCookieStore {
fileStore: FileCookieStore;
constructor(fileName: string) {
super();
this.fileStore = new FileCookieStore(fileName);
// Copy cookies from FileCookieStore to this
const refresh = () => {
this.fileStore.export(
{
push: (cookie: Cookie) =>
this.putCookie(cookie, (err) => {
if (err) {
logger.error("Error putting cookie", err);
}
}),
},
() => {
logger.debug("Cookies refreshed");
}
);
};
refresh();
watch(fileName).on("change", refresh);
}
}
const cookieJar = new CookieJar(
new RefreshingFileCookieStore(cookieFilePath)
);
const client = got.extend({
cookieJar,
headers: {
accept: "*/*",
},
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment