Getting started with js2

2 min read
Share:

We are assuming that you have installed node.js in your system, in case if you have not installed node.js, first install node.js.
To install js2 run the command given below:
[bash]
npm install js2
[/bash]

Let’s create a simple Hello World project, but first let’s create a project directory structure:
[bash]
mkdir helloWorldJs2
cd helloWorldJs2
mkdir scr lib
[/bash]

Now create a HelloWorld.js2 file in scr directory with the content given below:
[js]
class HelloWorld {
function sayHelloWorld() {
console.log(“Hello World”);
}
}
[/js]

To compile js2 file into js file in lib directory run the command given below:
[bash]
js2-node compile -f=node ./src ./lib
[/bash]

Above command will compile HellowWorld.js2 file and will generate HelloWorld.js file in lib directory. Now create a js script named as hello.js in scr directory with following content:
[js]
var HelloWorld = require(‘../lib/HelloWorld’).HelloWorld;
var helloWorld = new HelloWorld();
helloWorld.sayHelloWorld();
[/js]

Now run hello.js file with the command given below, And you will get Hello World printed at console.
[bash]
node src/hello.js
[/bash]

Amit Kumar
amit.kumar@intelligrape.com
in.linkedin.com/in/amitkumar0110
twitter.com/amit_kumar0110
More Blogs by Me

Leave a Reply

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