Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect file encoding in NodeJS?

How to detect which encoding was defined to a file?

I want something like this:

fs.getFileEncoding('C:/path/to/file.txt') // it returns 'UTF-8', 'CP-1252', ...

Is there a simple way to do it using a nodejs native function?

like image 637
Hemã Vidal Avatar asked Apr 26 '18 14:04

Hemã Vidal


1 Answers

You can use an npm module that does exactly this: https://www.npmjs.com/package/detect-character-encoding

You can use it like this:

const fs = require('fs');
const detectCharacterEncoding = require('detect-character-encoding');

const fileBuffer = fs.readFileSync('file.txt');
const charsetMatch = detectCharacterEncoding(fileBuffer);

console.log(charsetMatch);
// {
//   encoding: 'UTF-8',
//   confidence: 60
// }
like image 78
Eric Ly Avatar answered Oct 18 '22 21:10

Eric Ly