Project
This project is a class project called Language Identifier. It will take a text input in the Terminal and output what language the text is in. This will run from the Terminal only as it is an exercise in importing, configuring, and outputting data from a node package. We will be utilizing two packages to make our app work.
The first package is called
franc.
It takes a string input, identifies the language that the text is in, and returns a three digit code (based on the
ISO 639-3
standards) that represents the language. The second package is called
langs
and it will take the three digit code and return an object that includes the language name.
We then just have to process language.name for output. Simple.
We're going to start by creating a new project folder we'll call [whatLang]. Inside the folder we'll create an empty [index.js].
In the Terminal, navigate to this folder and enter [npm init] which is the process to create a new [package.json] file. In the [packages.json] file, we need to add our dependencies for the two packages we need to include, franc, and langs. So our [package.json] file should look like this:
- Json
- {
- "name": "lang",
- "version": "1.0.0",
- "description": "Language Identifier",
- "main": "index.js",
- "scripts": {
- "test": "echo \"Error: no test specified\" && exit 1"
- },
- "author": "badDoggy",
- "license": "ISC",
- "dependencies": {
- "franc": "^5.0.0",
- "langs": "^2.0.0"
- }
- }
So we now have our Project Folder [whatLang], our [project.json] file, and an empty [index.js] file that we'll get to shortly.
One thing that we are still missing is our [node_modules] folder with our installed packages, franc, and langs. And since they are listed as dependencies in our [package,json] file, we can just run [npm init] and it will install both of the missing packages, into the new [node_modules] folder, that it will create.
We should now have everything we need to make this app work. All that is left is to write the Js code into out [index.js] file to run our app:
- JavaScript
-
- const franc = require('franc');
- const langs = require('langs');
-
- const input = process.argv[2];
- const langCode = franc(input);
-
- if (langCode === 'und') {
- console.log('Undefined Language, please try more letters;')
- } else {
- const language = langs.where("3", langCode);
- console.log(`My best guess is: ${language.name}`);
- }
Pretty straight forward code here. We added an error trap in case [franc] can't determine the language. Also, on the input line, we are trapping the 3rd input argument by inputting [node] [index.js] [text], hence the command const input = process.argv[2];
So, to run this code, from the Terminal, in our project folder, we enter:
- node index.js 'Alle menneske er fødde til fridom'
and in th example, the output is:
- My best guess is: Norwegian Nynorsk