mcollina / msgpack5

A msgpack v5 implementation for node.js, with extension points / msgpack.org[Node]
MIT License
492 stars 76 forks source link

how to write to a file #81

Closed gcmartijn closed 4 years ago

gcmartijn commented 4 years ago

Hi

I asked this in a other repo but I get some errors and don't know how to do this. Nodejs is not a language that I use very often.

function createMsgPack(jsonData) {
    let bl = encode(jsonData)

    if (decode(bl) !== jsonData) {
        console.log("Cannot encode to msgPack")
        return false
    }

    // const file = fs.createWriteStream('file.mp')
    // bl.write(file); // error return this.utf8Write(string, 0, this.length); [TypeError: argument must be a string

    // const file = fs.createWriteStream('file.mp')
    // file.write(bl); // output a non encoded json file (with some weird signs)
}

Is it possible to write the encoded json to a file ?

mcollina commented 4 years ago

I would recommend to ask in stackoverflow or similar.

Something like this should work:

file = fs.createWriteStream('myfile')
bl.pipe(file)
gcmartijn commented 4 years ago

I did try that one but the answer is

xxxxx/index.js:120
    bl.pipe(file)
       ^

[TypeError: bl.pipe is not a function
  at createMsgPack (/xxxxx/index.js:120:8)
  at /xxxxxx/index.js:107:9
  at FSReqCallback.readFileAfterClose [as oncomplete] (internal/fs/read_file_context.js:63:3)
function createMsgPack(jsonData) {
    let bl = encode(jsonData)

    if (decode(bl) !== jsonData) {
        console.log("Cannot encode to msgPack")
        return false
    }

    const file = fs.createWriteStream('myfile.mp')
    bl.pipe(file)

}
gcmartijn commented 4 years ago

I can write but the output is not encoded to message pack

If I do this:

    const file = fs.createWriteStream('myfile.mp')
    fs.writeFileSync('myfile2.mp', bl);

But the output is just the json file but then with some weird starting characters. Not the compressed/encoded message pack file.

Új{
  "x": {
    "y": "z"
  },
  .... (etc)
mcollina commented 4 years ago

I would recommend to study Node.js and JavaScript before using this module.

gcmartijn commented 4 years ago

Going to give this a try: I'm only need to convert a json file to msgpack ;)

https://github.com/ludocode/msgpack-tools