Python Pickle Parser for JavaScript

0.2.1 · active · verified Wed Apr 22

The `pickleparser` library provides a pure JavaScript and TypeScript implementation for parsing Python's pickle serialization format. It supports all pickle protocol versions from 0 to 5, allowing developers to deserialize Python objects directly within Node.js environments and web browsers. Currently stable at version 0.2.1, the project appears to have an active release cadence, frequently adding support for new opcodes and refining its API. A key differentiator is its full protocol support and its utility for converting pickle data to JSON, including a bundled `pickletojson` CLI tool, without relying on Python runtimes. It offers `ParserOptions` for customizing the unpickling process, making it flexible for various use cases.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates how to read a Python pickle file from disk using Node.js, parse it with `pickleparser`, and log the resulting JavaScript object to the console, including a `BigInt` replacer for `JSON.stringify()`.

import fs from 'node:fs/promises';
import path from 'node:path';
import { Parser } from 'pickleparser';

async function unpickleFile(filePath: string) {
    try {
        // Read the pickle file as raw binary data (Buffer in Node.js)
        const pklData = await fs.readFile(filePath, null); 
        const buffer = Buffer.from(pklData);

        // Initialize the parser and parse the buffer
        const parser = new Parser();
        const obj = parser.parse(buffer);
        
        // Log the parsed object. Use a replacer for JSON.stringify to handle BigInts.
        console.log(JSON.stringify(obj, (key, value) =>
            typeof value === 'bigint' ? value.toString() + 'n' : value
        , 2));
    } catch (error) {
        console.error(`Error unpickling file ${filePath}:`, error);
    }
}

// Example usage: Ensure a pickle file exists at the specified path.
// For demonstration, we use an environment variable or a default.
unpickleFile(process.env.PICKLE_FILE_PATH ?? './example.pkl');

// To create a dummy pickle file for testing (run this in Python):
// import pickle
// data = {'message': 'Hello from Python!', 'value': 12345678901234567890, 'items': [1, 2, 3]}
// with open('example.pkl', 'wb') as f:
//     pickle.dump(data, f, pickle.HIGHEST_PROTOCOL)

view raw JSON →