7

I'm new to JavaScript and Node.js. So, I have a JSON file and I want to encode this file to a UTF-8 JSON file. How is it possible with Node.js?

The source JSON file is generated by another framework and contains maybe BOMs, but I need a UTF-8 JSON file without BOMs to handle it.

7
  • Whilst I'm not sure this is an exact dupe, this question may help a lot. Commented Jul 5, 2017 at 9:02
  • This converts me a string, but I want to change the encoding of a file. So, maybe I have to read the content of the file, encode it to utf-8 and save it maybe to another file. But I don't know to to implement in JavaScript. Commented Jul 5, 2017 at 9:05
  • Load the file, read the contents, convert, save file? Sound's good to me Commented Jul 5, 2017 at 9:07
  • theoretically yes, but how to implement it with a little example... Commented Jul 5, 2017 at 9:08
  • 2
    "The source JSON file is generated by another framework and contains maybe BOMs" — Then it isn't JSON: Implementations MUST NOT add a byte order mark to the beginning of a JSON text. Commented Jul 5, 2017 at 9:11

1 Answer 1

11
var fs = require('fs');
const detectCharacterEncoding = require('detect-character-encoding'); //npm install detect-character-encoding
var buffer = fs.readFileSync('filename.txt');
var originalEncoding = detectCharacterEncoding(buffer);
var file = fs.readFileSync('filename.txt', originalEncoding.encoding);
fs.writeFileSync('filename.txt', file, 'UTF-8');

How does this work?

When fs reads in a file, it converts it from the encoding of the file to the format that JS uses.

After that, when fs writes the file, it converts the string stored by JS to UTF-8 and writes it to file.

Sign up to request clarification or add additional context in comments.

1 Comment

And if I don't know the original encoding of the file? It's generated by another framework and I don't know the original source encoding of the source JSON file.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.