nginx/njs

First chunk detection in js_body_filter

Closed this issue · 1 comments

How to detect the chunk is first in js_body_filter?
For exam I want to encrypt first 500 byte of file to response.

Hi @rezakho,

Try something like this (not tested though), you have to implement encode() by yourself.

let chunks = [];
let total = 0;
function encrypt_first_500bytes(r, data, flags) {
    if (total + data.length > 500) {
        let left = 500 - total;
        chunks.push(data.slice(0, left));
        // send the encrypted 500 bytes first
        r.sendBuffer(encode(chunks.join("")), {});
        // send what is left in the current chunk
        r.sendBuffer(data.slice(left), flags);
        // stop filtering
        r.done();
        return;
    }
    
    // collect chunks, until you get 500 bytes or more
    total += data.length;
    chunks.push(data);
}