How to get file character encoding in Node.js ?

Computer reads data in binary representation, that is why we need a way to convert text characters into binary data, this is done with the help of character encoding.

Most popular character encoding types are ASCII and Unicode. Unicode is defined as UTF-8, UTF-16, etc.

We can use a module called ‘detect-file-encoding-and-language‘ to get the character encoding of file in node.js

Syntax:

languageEncoding(pathToFile).then(
    fileInfo => // Do anything
);

Parameters:

  • pathToFile: (Relative or Absolute)Path of the actual file.

Return Value:

An Object having following values, { language: french, encoding: CP1252, confidence: 0.99 }

Setting up environment and Execution:

Step 1: Initialize node.js project

npm init

Step 2: Install required modules

npm install detect-file-encoding-and-language

Step 3: Create a text file

Filename- a.txt

Beginner for Beginner

Step 4: Code in index.js file

index.js




import languageEncoding from "detect-file-encoding-and-language"
  
const pathToFile = "./a.txt"
  
languageEncoding(pathToFile)
    .then(fileInfo => console.log(fileInfo.encoding))
    .catch(err => console.log(err));


Step 5: Run index.js File

node index.js

Output: See output in console