Node JSPowerShell

Build RESTful API using Node JS and consume it using PowerShell | Google Translate

I started my session by thanking matheuss and one raised voice  “Hey, Thanks Mr.Sundar Pichai!” – Yay! Good One! I just lost my focus and managed to push back! Yes, I really appreciate the author who made this possible nearly 2 years before. So, what’s new I can do using this NPM package? With no wait we started to demo our PowerShell snippets which consumes our REST endpoints built using Node JS.

#region - English to French
$Texts = "Good Morning" , "Good Afternoon" , "Good Night" 
foreach($Text in $Texts) {
    $Result = Invoke-RestMethod -Uri "http://localhost:3000/translate/$($Text)/en/fr"
    [pscustomobject]@{
        "Actual Text" = $Text
        "Translated Text" = $Result.text 
        "Actual Language" = $Result.from.language.iso
    }
}
#endregion

#region - English to Dutch
$Texts = "Good Morning" , "Good Afternoon" , "Good Night" 
foreach($Text in $Texts) {
    $Result = Invoke-RestMethod -Uri "http://localhost:3000/translate/$($Text)/en/nl"
    [pscustomobject]@{
        "Actual Text" = $Text
        "Translated Text" = $Result.text 
        "Actual Language" = $Result.from.language.iso
    }
    
}
#endregion

Output is illustrated below

It’s really easy to set it up! Check out the code below.

Server.JS

var express = require('express'),
    app = express(),
    translate = require('google-translate-api');

app.get("/", function (request, response) {
    response.send("Hello World!")
})

app.get("/translate/:text", function (request, response) {
    translate(request.params.text, { to: 'en' }).then(result => {
        response.send(result)
    }).catch(err => {
        response.send(err)
    })
})

app.get("/translate/:text/:from/:to", function (request, response) {
    translate(request.params.text, { from: request.params.from, to: request.params.to }).then(result => {
        response.send(result)
    })
})

app.listen(3000)
console.log("Your Application is Running in Port 3000")

Package.json

{
  "name": "xgoogletranslate",
  "version": "1.0.0",
  "description": "API for google translate",
  "main": "server.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "node server.js"
  },
  "author": "Chendrayan Venkatesan",
  "license": "ISC",
  "dependencies": {
    "express": "^4.16.3",
    "google-translate-api": "^2.3.0"
  }
}

Usage:

Leave a Reply

Your email address will not be published. Required fields are marked *