NodeJS write binary buffer into a file

后端 未结 2 2068
感动是毒
感动是毒 2020-12-05 23:37

I can\'t rewrite a file that I am getting from a binary buffer, I have checked with the original file and all bytes are the same.

This is the file create from NodeJ

相关标签:
2条回答
  • 2020-12-05 23:44

    You can try this:

    var writeFileSync = function (path, buffer, permission) {
        permission = permission || 438; // 0666
        var fileDescriptor;
    
        try {
            fileDescriptor = fs.openSync(path, 'w', permission);
        } catch (e) {
            fs.chmodSync(path, permission);
            fileDescriptor = fs.openSync(path, 'w', permission);
        }
    
        if (fileDescriptor) {
            fs.writeSync(fileDescriptor, buffer, 0, buffer.length, 0);
            fs.closeSync(fileDescriptor);
        }
    }
    
    // then writeFileSync('path_to_your_file', your_buffer);
    
    0 讨论(0)
  • 2020-12-05 23:54

    I am not sure if this would help but try to change the b variable to the bytes variable in the line below at least you would be able to view the file in a test editor

    fs.writeFile("test.txt", b,  "binary",function(err) { });
    

    If you would like to have the numbers space separated try the code below:

    var fs = require('fs');
    
    var foo = "71%73%70%56%57%97%50%0%50%0%247%0%0%150%140%115%102%94%69%198%187%159%123%114%90%71%71%71%138%129%101%202%193%166%201%193%172%238%234%221%200%197%188%140"
    var bytes = foo.split("%");
    
    var b = new Buffer(bytes.length);
    var c = "";
    for (var i = 0;i < bytes.length;i++) {
        b[i] = bytes[i];
        c = c + " " + bytes[i]
    }
    
    fs.writeFile("test.txt", c,  "binary",function(err) {
        if(err) {
            console.log(err);
        } else {
            console.log("The file was saved!");
        }
    });
    
    0 讨论(0)
提交回复
热议问题