Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a file to a UTF-8 file in Node.js

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.

like image 790
GRme Avatar asked Jul 05 '17 09:07

GRme


1 Answers

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.

like image 108
skiilaa Avatar answered Oct 18 '22 21:10

skiilaa