Search code examples
node.jshttpexpressbsonbody-parser

How to read BSON data in Express.js with body parser


I have a Node.js API using Express.js with body parser which receives a BSON binary file from a python client.

Python client code:

data = bson.BSON.encode({
    "some_meta_data": 12,
    "binary_data": binary_data
})
headers = {'content-type': 'application/octet-stream'}
response = requests.put(endpoint_url, headers=headers, data=data)

Now I have an endpoint in my Node.js API where I want to deserialize the BSON data as explained in the documentation: https://www.npmjs.com/package/bson. What I am struggling with is how to get the binary BSON file from the request.

Here is the API endpoint:

exports.updateBinary = function(req, res){
    // How to get the binary data which bson deserializes from the req?
    let bson = new BSON();
    let data = bson.deserialize(???);
    ...
}

Solution

  • You'll want to use https://www.npmjs.com/package/raw-body to grab the raw contents of the body.

    And then pass the Buffer object to bson.deserialize(..). Quick dirty example below:

    const getRawBody = require("raw-body");
    
    app.use(async (req, res, next) => {
        if (req.headers["content-type"] === "application/octet-stream") {
            req.body = await getRawBody(req)
        }
        next()
    })
    

    Then just simply do:

    exports.updateBinary = (req, res) => {
        const data = new BSON().deserialize(req.body)
    }