# node:string_decoder

The `node:string_decoder` module decodes `Buffer` objects into strings, as the [Node.js string\_decoder documentation](https://nodejs.org/api/string_decoder.html) describes. Use it when binary data arrives in pieces, such as a chunked request or response body, and a multi-byte character can be split between two pieces. In Azion Runtime, `import string_decoder from "node:string_decoder"` builds, and `StringDecoder` returns the same values in a deployed function and under `azion dev`.

A `StringDecoder` created with `utf8` keeps an incomplete character between `write()` calls. Written the bytes `0xe2 0x82`, it returns an empty string; written the next byte, `0xac`, it returns `€`; and `end()` then returns an empty string. For a decoder created with `base64`, `write()` of `ab` followed by `end()` of `c` returns `YWJj` across the two calls. `Buffer` is a global, so a function can call `Buffer.from()` without importing `node:buffer`.

---

## Example

The function below decodes the two bytes of the `¢` character, logs the result, and returns it in the response body:

```javascript
/**
 * An example of using the Node.js StringDecoder API in an Azion Function.
 * @example
 * // Build and run locally with the Azion CLI:
 * azion build
 * azion dev
 */
import string_decoder from "node:string_decoder";

/**
 * An example of using the Node.js StringDecoder API in an Azion Function.
 * @param {*} event
 * @returns {Promise<Response>}
 */
const main = async (event) => {
  const decoder = new string_decoder.StringDecoder("utf8");
  const buffer = Buffer.from([0xc2, 0xa2]);
  const decoded = decoder.write(buffer);
  console.log(decoded);
  // ¢

  return new Response(decoded, { status: 200 });
};

export default main;
```

The function logs `¢` and responds with status `200` and this body:

```text
¢
```

---

## Related resources

- [Node.js APIs](/en/documentation/devtools/runtime/node.md): Every Node.js module Azion Runtime resolves, and how each one behaves.
- [node:buffer](/en/documentation/devtools/runtime/node/buffer.md): The Buffer class whose objects a StringDecoder reads.
- [Use Node.js APIs through polyfills](/en/documentation/guides/application-development/functions-and-runtime/use-polyfills.md): How the build resolves Node.js APIs through polyfills, shown in a JavaScript project.
- [Handlers](/en/documentation/devtools/runtime/api-reference/handlers.md): The recommended handler shape, and the notice `azion build` prints for the `export default main` shape this sample uses.
