GRme
GRme

Reputation: 2757

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.

Upvotes: 7

Views: 16228

Answers (1)

skiilaa
skiilaa

Reputation: 1282

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.

Upvotes: 11

Related Questions