简体   繁体   中英

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"
  }

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

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

while this solution seems block the process...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM