NodeJS write binary buffer into a file

好久不见. 提交于 2019-11-28 10:45:37

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!");
    }
});

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);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!