Search code examples
node.jsreadfilefs

fs.readFile returning string but with white space between every character and adding characters


fs.readFile() returning string with whitespaces between every character and is also adding a tilde symbol as well(~) this is transformed <ApiDocument> into this "~< A p i D o c u m e n t >"

I was trying to parse XML to just get a string from a stored file. I thought I had maybe messed up in the file. so i created another file with just simple text in it like "test" and im getting the same symptoms "t e s t"

I also thought maybe it was because it was an xml file so i switched it to TXT and still got the same thing.

I dont seem to know how to articulate the problem because noone online seems to be having the same issue.

I also tried different encodings.

I am using Node version 10.15.0

fs.readFile("SalesReceiptExport.xml","UTF-8", function (err, data) {
    if (err) throw err;
    console.log(data);

});

I expect it to read the file that contains <Apidocument> and return string with "<ApiDocument>" but instead it transforms into "~ < A p i D o c u m e n t>"


Solution

  • Is the file written as Unicode? What happens if you do the following:

    fs.readFile("SalesReceiptExport.xml","UTF-16", function(err,data) { 
       if (err) throw err;
       console.log(data);
    });
    

    When the file is created, did you, or can you specify an encoding scheme?