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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With