Vinay S Shenoy
Vinay S Shenoy

Reputation: 4028

CRC32 checksum is not getting calculated in node.js

I'm writing a node.js server where I accept a file along with a CRC32 checksum in a multipart request. I am using busboy and crc node modules to handle multipart requests and CRC operations in node.

In the busboy's finish event, I am attempting to calculate the CRC32 checksum of the saved file and validating it against the received checksum.

My problem is that in the finish event, the checksum is always calculated as 0. If I manually run the CRC32 checksum against the same file, the checksum gets calculated properly.

Here's the code snippet I use to handle the multipart request with crc32 calculation:

var busboy = new Busboy({ headers : request.headers});
var saveTo;
var crc32;
busboy.on('file', function (fieldname, file, filename, encoding, mimetype) {
    saveTo = path.join('files', '/', filename);
    file.pipe(fs.createWriteStream(saveTo));
});

busboy.on('field', function(fieldname, val, fieldnameTruncated, valTruncated) {
    if(fieldname == 'checksum') {
        crc32 = val;
    }
});

busboy.on('finish', function() {
    var savedFileCrc32 = crc.crc32(fs.readFileSync(saveTo)).toString(16);
    console.log("CRC32 of saved file: " + savedFileCrc32 + " file: " + saveTo);
});
request.pipe(busboy);

My console always prints CRC32 of saved file: 0 file: files/image.jpg

However, if I run a node program to calculate the CRC32 checksum of the file that was just created, it works perfectly and prints the checksum.

The image is also getting saved properly. In the finish event, if I open a read stream onsaveTo and read out the bytes, the image is getting read, so the file already exists.

Any idea what the problem could be?

Upvotes: 0

Views: 2186

Answers (1)

tgo
tgo

Reputation: 1545

The only thing I can think of is that the write is not finished by the time you do the readFileSync(). Can you check if the file exists before reading ?

I am also wondering if it's not in fact a duplicate of this.

Upvotes: 1

Related Questions