Introduction to language-detect
The language-detect library is an essential tool for developers who need to determine the language of a given piece of text. It provides a simple API with numerous functionalities, enabling you to seamlessly integrate language detection into your applications. This guide will introduce you to the basic and advanced uses of the language-detect API, complete with code snippets and an app example.
Basic Usage
To get started with language-detect, you’ll need to install the library:
$ npm install language-detect
Once installed, you can easily use the library to detect languages.
const LanguageDetect = require('language-detect'); const detector = new LanguageDetect(); const language = detector.detect('Bonjour tout le monde'); console.log(language);
Advanced API Examples
The language-detect library includes a variety of useful APIs. Here are a few examples:
1. Detect Multiple Languages
const languages = detector.detect('Bonjour tout le monde. Hello world.', 2); console.log(languages);
2. Detect Language with Probability
const languagesWithProbability = detector.detectWithProbability('Hola mundo'); console.log(languagesWithProbability);
3. Get Supported Languages
const supportedLanguages = detector.getLanguages(); console.log(supportedLanguages);
Building a Language Detection App
Let’s build a simple app that uses the language-detect API to identify the language of a given text:
1. Setting up the Project
$ mkdir language-detect-app $ cd language-detect-app $ npm init -y $ npm install language-detect express body-parser
2. Creating the Server
const express = require('express'); const bodyParser = require('body-parser'); const LanguageDetect = require('language-detect');
const app = express(); const detector = new LanguageDetect();
app.use(bodyParser.json());
app.post('/detect', (req, res) => {
const { text } = req.body;
const languages = detector.detect(text, 3);
res.json({ languages });
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
With this setup, you can send a POST request to /detect
with a JSON body containing the text, and the server will respond with the top three detected languages.
Example POST request:
POST /detect HTTP/1.1 Host: localhost:3000 Content-Type: application/json {
"text": "Hello world! Bonjour tout le monde!"
}
Example Response:
{
"languages": ["english", "french"]
}
With language-detect, you can create more complex apps that handle multilingual inputs with ease.
Happy coding!
Hash: e14d684b9aae0ff3889c63a4a9304eeb0940498f226e8f541780398f1e9a10f3