Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript can load Python pickle dumped string but not file

Please see the following test code, I can use jpickle library to decode the Python pickle dumped string back.

(base):~/python 
Python 3.7.3 (default, Mar 27 2019, 16:54:48) 
[Clang 4.0.1 (tags/RELEASE_401/final)] :: Anaconda, Inc. on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import pickle
>>> pickle.dumps('Hello Python!')
b'\x80\x03X\r\x00\x00\x00Hello Python!q\x00.'
>>> 
(base)~$ node
> const jpickle = require('jpickle');
undefined
> jpickle.loads('\x80\x03X\r\x00\x00\x00Hello Python!q\x00.')
'Hello Python!'

While when I am trying to write the pickled string to a file, I cannot load it back in nodejs. what's my mistake here? Thank you!

python code:

import pickle
with open('test.dat', 'wb') as fout:
    pickle.dump('Hello Python!', fout)

JS:

const fs = require('fs');
const jpickle = require('jpickle');
const binary = fs.readFileSync('test.dat');
const data = jpickle.loads(binary)
console.log(data)

error msg:

node_modules/jpickle/lib/jpickle.js:341
            throw "Unhandled opcode '" + opcode + "'";
            ^
Unhandled opcode '128'

jpickle in package.json, need to be installed from GitHub, which is the latest version:

    "jpickle": "git+https://github.com/jlaine/node-jpickle.git"
  }
like image 969
dli Avatar asked May 17 '26 03:05

dli


1 Answers

This seems worked for me. Thank Tomalak for the input.

const binary = fs.readFileSync('test.dat', "binary");

while this solution seems block the process...

like image 102
dli Avatar answered May 18 '26 21:05

dli