8

How can I find out what character encoding a given text file has?

var inputFile = "filename.txt";
var file = fs.readFileSync(inputFile); 
var data = new Buffer(file, "ascii");
var fileEncoding = some_clever_function(file);
if (fileEncoding !== "utf8") {
    // do something
}

Thanks

2 Answers 2

6

You can try to use external module, such as https://www.npmjs.com/package/detect-character-encoding

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

1 Comment

that's exactly what I've been looking for, thanks :)
2

The previously mentioned module works for me too. Alternatively you could have a look at detect-file-encoding-and-language which I'm using at the moment.

Installation:

$ npm install detect-file-encoding-and-language

Usage:

// index.js

const languageEncoding = require("detect-file-encoding-and-language");

const pathToFile = "/home/username/documents/my-text-file.txt"

languageEncoding(pathToFile).then(fileInfo => console.log(fileInfo));
// Possible result: { language: japanese, encoding: Shift-JIS, confidence: { language: 0.97, encoding: 1 } }

Comments

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.