Check if a file is binary or ASCII with Node.js?

前端 未结 3 750
长情又很酷
长情又很酷 2021-01-01 13:50

I\'m wondering what would be the best way to check if a file is binary or ASCII with Node.js?

There appears to be two ways not specific to node.js:

3条回答
  •  长发绾君心
    2021-01-01 14:31

    I came here from google but as I couldn't find a satisfactory answer, I took another approach which works for me:

    const string_to_test = "I am just a piece of text";
    //const binary_to_test = "��˰!1�H��1�1����!H�=u�!�";
    if(/\ufffd/.test(string_to_test) === true){
        console.log("I'm 'binary'");
    }else{
        console.log("I'm proper text");
    }
    

    How does it works? If you try to open binary data in a normal way (without using a hex editor), it will encounter some rendering problems which translate to you as a succession of this weird character � called "Replacement character".

提交回复
热议问题