Google translator is a service which helps to convert one language to the other. This has many practical applications in day to day life. Internationalization of a web application is one such application. Internationalization or i18n is process of creating a web application in a way that it can be served in multiple local languages across the world. This only makes the app more accessible to a wider audience using different languages. In the following article we'll see how we can use google translator in a node.js based application.
In the first section we've created a project on google cloud and we've created
the required API Key. In this section we'll see what needs to be done on the
node.js side. Note that we're showing you the application using a very basic
node script. You can easily use the same or equivalent code on more complex
and advanced application e.g. web application written using frameworks like
express, sails or hapi.
Let's get going on the nodejs part
google-translate
package from npm for using google translator
API. We can install it from npm using the following command :
npm install google-translate
node-translate.js
and add the following code to it. Don't forget to replace the api key
with your actual api key.
var api = "YOUR_GOOGLE_TRANSLATOR_KEY_HERE";
var googleTranslate = require('google-translate')(api);
var text = 'I am using google translator to convert this text to spanish'
console.log("English :>",text);
googleTranslate.translate(text, 'es', function(err, translation) {
console.log("Spanish :>",translation.translatedText);
});
We can run the code using the following command and we will get the output shown below:
G:\google-translator>node node-translate.js
English :> I am using google translator to convert this text to spanish
Spanish :> Estoy usando el traductor de google para convertir este texto al espa�ol
In this article we learned how to integrate google translate api with a nodejs application.