A .docXfile is not a UTF-8 string (it's a binary ZIP file) so when you read it into a Buffer object and then call .toString() on it, you're assuming it is already encoding as UTF-8 in the buffer and you want to now move it into a Javascript string. That's not what you have. Your binary data will likely encounter things that are invalid in UTF-8 and those will be discarded or coerced into valid UTF-8, causing an irreversible change.

What Buffer.toString() does is take a Buffer that is ALREADY encoded in UTF-8 and puts it into a Javascript string. See this comment in the doc,

If encoding is 'utf8' and a byte sequence in the input is not valid UTF-8, then each invalid byte is replaced with the replacement character U+FFFD.

So, the code you show in your question is wrongly assuming that Buffer.toString() takes binary data and reversibly encodes it as a UTF8 string. That is not what it does and that's why it doesn't do what you are expecting.

Your question doesn't describe what you're actually trying to accomplish. If you want to do something useful with the .docX file, you probably need to actually parse it from it's binary ZIP file form into the actual components of the file in their appropriate format.

Now that you explain you're trying to store it in localStorage, then you need to encode the binary into a string format. One such popular option is Base64 though it isn't super efficient (size wise), but it is better than many others. See Binary Data in JSON String. Something better than Base64 for prior discussion on this topic. Ignore the notes about compression in that other answer because your data is already ZIP compressed.

Answer from jfriend00 on Stack Overflow
๐ŸŒ
Node.js
nodejs.org โ€บ api โ€บ buffer.html
Buffer | Node.js v26.10.0 Documentation
Unlike 'utf8', each character in the string will be encoded using either 2 or 4 bytes. Node.js only supports the little-endian variant of UTF-16. 'latin1': Latin-1 stands for ISO-8859-1. This character encoding only supports the Unicode characters from U+0000 to U+00FF. Each character is encoded using a single byte. Characters that do not fit into that range are truncated and will be mapped to characters in that range. Converting a Buffer into a string using one of the above is referred to as decoding, and converting a string into a Buffer is referred to as encoding.
๐ŸŒ
W3Schools
w3schools.com โ€บ nodejs โ€บ met_buffer_tostring.asp
Node.js buffer toString() Method
The toString() method returns the buffer object according to the specified encoding.
Discussions

node.js - Converting a nodejs buffer to string and back to buffer gives a different result in some cases - Stack Overflow
From better privacy to our new ChatGPT plugin, here's what's new on Stack... ... 2 NodeJS UTF8 Encoding A Buffer Then Decoding That UTF8 String Produces A Buffer With Different Content More on stackoverflow.com
๐ŸŒ stackoverflow.com
node.js - convert streamed buffers to utf8-string - Stack Overflow
Are the existing open-ended question tags enough to define the scope of... Looking ahead, starting conversations, and seizing the moment ... 2 NodeJS UTF8 Encoding A Buffer Then Decoding That UTF8 String Produces A Buffer With Different Content More on stackoverflow.com
๐ŸŒ stackoverflow.com
Converting buffer to string
Hi, I am trying to convert a buffer data to string data Buffer data i am pushing in as follows, [123,34,100,97,116,97,34,58,34,52,49,49,48,48,52,34,44,32,34,112,111,114,116,34,58,50,44,32,34,116,105,109,101,34,58,34,105,109,109,101,100,105,97,116,101,108,121,34,125,0] the data displays when ... More on discourse.nodered.org
๐ŸŒ discourse.nodered.org
7
1
February 4, 2020
node.js - Convert string to buffer Node - Stack Overflow
Try just Buffer(bufStr) instead until you upgrade. 2016-05-25T12:32:25.467Z+00:00 ... Actually, it should be 'utf8' and not 'utf-8'. Edited the answer. 2016-10-09T12:07:04.437Z+00:00 ... iconv-lite is better, because it uses standard charset names from world of client js (like utf-8), instread of NodeJS ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
๐ŸŒ
Toptal
toptal.com โ€บ external-blogs โ€บ adeva โ€บ convert-node-js-buffer-to-string
How to Convert Node.js Buffer to String | Toptalยฎ
May 26, 2026 - In a nutshell, itโ€™s easy to convert a Buffer object to a string using the toString() method. Youโ€™ll usually want the default UTF-8 encoding, but itโ€™s possible to indicate a different encoding if needed.
๐ŸŒ
Educative
educative.io โ€บ answers โ€บ what-is-the-nodejs-buffertostring-method
What is the Node.js Buffer.toString() method?
In Node.js, the Buffer.toString() method is used to decode or convert a buffer to a string, according to the specified character encoding type.
๐ŸŒ
Joshtronic
joshtronic.com โ€บ 2022 โ€บ 11 โ€บ 27 โ€บ convert-a-buffer-to-a-string-in-nodejs
Convert a buffer to a string in Node.js - Joshtronic
November 27, 2022 - While we already know what the buffer contains, since we defined the string, let's take a look at what the buffer looks like, so we can get a sense for how things would look when we don't know what the buffer contains: console.log(buffer); // <Buffer 49 20 61 6d 20 61 20 62 75 66 66 65 72 21> The buffer is effectively just an array of integers that represent the data that it contains. To get a string back out of the buffer, simply use .toString():
Find elsewhere
Top answer
1 of 1
7

A .docXfile is not a UTF-8 string (it's a binary ZIP file) so when you read it into a Buffer object and then call .toString() on it, you're assuming it is already encoding as UTF-8 in the buffer and you want to now move it into a Javascript string. That's not what you have. Your binary data will likely encounter things that are invalid in UTF-8 and those will be discarded or coerced into valid UTF-8, causing an irreversible change.

What Buffer.toString() does is take a Buffer that is ALREADY encoded in UTF-8 and puts it into a Javascript string. See this comment in the doc,

If encoding is 'utf8' and a byte sequence in the input is not valid UTF-8, then each invalid byte is replaced with the replacement character U+FFFD.

So, the code you show in your question is wrongly assuming that Buffer.toString() takes binary data and reversibly encodes it as a UTF8 string. That is not what it does and that's why it doesn't do what you are expecting.

Your question doesn't describe what you're actually trying to accomplish. If you want to do something useful with the .docX file, you probably need to actually parse it from it's binary ZIP file form into the actual components of the file in their appropriate format.

Now that you explain you're trying to store it in localStorage, then you need to encode the binary into a string format. One such popular option is Base64 though it isn't super efficient (size wise), but it is better than many others. See Binary Data in JSON String. Something better than Base64 for prior discussion on this topic. Ignore the notes about compression in that other answer because your data is already ZIP compressed.

๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ node-js-buffer-tostring-method
Node.js Buffer.toString() Method | GeeksforGeeks
October 13, 2021 - NodeJS String Decoder ยท NodeJS ... Article ยท Like ยท Report ยท The Buffer.toString() method is used to decode a buffer data to string according to the specified encoding type....
๐ŸŒ
Daniel Lemire's blog
lemire.me โ€บ blog โ€บ 2023 โ€บ 12 โ€บ 08 โ€บ fast-buffer-to-string-conversion-in-javascript-with-a-lookup-table
Fast Buffer-to-String conversion in JavaScript with a Lookup Table โ€“ Daniel Lemire's blog
December 8, 2023 - If the buffer has length 3, then I have four possible candidate strings (age, ect, rtt, via). I can differentiate them by looking only at the first character. The logic is much the same: case 3: switch (s[0]) { case 97: case 65: // check that the buffer is equal to age and return it if so if ((s[1] == 103 || s[1] == 71) && (s[2] == 101 || s[2] == 69)) { return "age"; } break; case 101:case 69: // check that the buffer is equal to ect and return it if so if ((s[1] == 99 || s[1] == 67) && (s[2] == 116 || s[2] == 84)) { return "ect"; } break; case 114:case 82: // check that the buffer is equal to rtt and return it if so if ((s[1] == 116 || s[1] == 84) && (s[2] == 116 || s[2] == 84)) { return "rtt"; } break; case 118:case 86: // check that the buffer is equal to via and return it if so if ((s[1] == 105 || s[1] == 73) && (s[2] == 97 || s[2] == 65)) { return "via"; } break; default: break; }
๐ŸŒ
Melvin George
melvingeorge.me โ€บ blog โ€บ convert-string-buffer-nodejs
How to convert a String to Buffer and vice versa in Node.js | MELVIN GEORGE
September 19, 2020 - // buffer const str = "Hey. this is a string!"; const buff = Buffer.from(str, "utf-8"); // convert buffer to string const resultStr = buff.toString(); console.log(resultStr); //Hey.
Top answer
1 of 2
319

Single Buffer

If you have a single Buffer you can use its toString method that will convert all or part of the binary contents to a string using a specific encoding. It defaults to utf8 if you don't provide a parameter, but I've explicitly set the encoding in this example.

var req = http.request(reqOptions, function(res) {
    ...

    res.on('data', function(chunk) {
        var textChunk = chunk.toString('utf8');
        // process utf8 text chunk
    });
});

Streamed Buffers

If you have streamed buffers like in the question above where the first byte of a multi-byte UTF8-character may be contained in the first Buffer (chunk) and the second byte in the second Buffer then you should use a StringDecoder. :

var StringDecoder = require('string_decoder').StringDecoder;

var req = http.request(reqOptions, function(res) {
    ...
    var decoder = new StringDecoder('utf8');

    res.on('data', function(chunk) {
        var textChunk = decoder.write(chunk);
        // process utf8 text chunk
    });
});

This way bytes of incomplete characters are buffered by the StringDecoder until all required bytes were written to the decoder.

2 of 2
-5
var fs = require("fs");

function readFileLineByLine(filename, processline) {
    var stream = fs.createReadStream(filename);
    var s = "";
    stream.on("data", function(data) {
        s += data.toString('utf8');
        var lines = s.split("\n");
        for (var i = 0; i < lines.length - 1; i++)
            processline(lines[i]);
        s = lines[lines.length - 1];
    });

    stream.on("end",function() {
        var lines = s.split("\n");
        for (var i = 0; i < lines.length; i++)
            processline(lines[i]);
    });
}

var linenumber = 0;
readFileLineByLine(filename, function(line) {
    console.log(++linenumber + " -- " + line);
});
๐ŸŒ
Leyaa
leyaa.ai โ€บ codefly โ€บ learn โ€บ nodejs โ€บ part-1 โ€บ nodejs-buffer-to-string-conversion โ€บ try
Buffer to string conversion in Node.js - Interactive Code Practice | Leyaa.ai
A Buffer holds raw binary data that is not human-readable. The toString() method converts this raw data into a readable string using a specified encoding, defaulting to UTF-8.
๐ŸŒ
Node-RED
discourse.nodered.org โ€บ general
Converting buffer to string - General - Node-RED Forum
February 4, 2020 - Hi, I am trying to convert a buffer data to string data Buffer data i am pushing in as follows, [123,34,100,97,116,97,34,58,34,52,49,49,48,48,52,34,44,32,34,112,111,114,116,34,58,50,44,32,34,116,105,109,101,34,58,34,105,109,109,101,100,105,97,116,101,108,121,34,125,0] the data displays when it converted to string as below, {"data":"411004", "port":2, "time":"immediately"} how should i need to proceed in node red?
๐ŸŒ
Scaler
scaler.com โ€บ home โ€บ topics โ€บ nodejs โ€บ buffers and string decoders in node.js
Buffers and String Decoders in Node.js - Scaler Topics
May 4, 2023 - StringDecoder is a built-in Node.js module, so we don't need to install it. You can simply import it with the following statement. ... The buffer data is decoded into a string using the NodeJS StringDecoder. Buffers are used to store streams of binary data.
๐ŸŒ
DEV Community
dev.to โ€บ melvin2016 โ€บ how-to-convert-a-string-to-buffer-and-vice-versa-in-node-js-5op
How to convert a String to Buffer and vice versa in Node.js - DEV Community
September 19, 2020 - The method accepts a valid string as the first argument. ... To convert a Buffer to a String, you can use the toString() in the Buffer object.