×

Search anything:

Online Compiler in Node.JS

Binary Tree book by OpenGenus

Open-Source Internship opportunity by OpenGenus for programmers. Apply now.

Reading time: 40 minutes | Coding time: 30 minutes

If you are a programmer then you definetly must have used an online compiler in your life but have you ever wondered "Can I make something like this?" and the answer is "Yes".

You can definetly make your own online compiler for the programming language you want to code. In this article you will learn how to build your own Online Compiler in Node.JS (a JavaScript framework). Let's get started:-

First of all let us look how our compiler is going to GET request and POST response on the server and the flow of the all the process from selecting a programming language and defining it's parameters:-
1->In index.html file we will define our form with the text-area to write our code,options to select the programming langauge with input or without input respectively and submit button to submit the code to get the output;
2->In the main app.js file we will define all our funtions for the language and to delete the temporary files.
3->In the first step will define the POST function from the '/compilecode' route where we will extract all the information entered by the users that is the code written by the user,language selected,input,and if input is selected or not and store each of them in different variables.Then we will compare the language selected by the user is equal the functions defined the app.js file call the functions related to the programming language from the compilex modules.
4->Now what will happen under the hood is that compilex will generate a temporary file based on the compiler in your pc (gcc for linux and g++ for windows for C or C++ language) and will generate a output if the code is correct and send that output to the server or generate the errors if any.
5->This is the last or optional step if you want to remove all the temporary files generated we will define a flush function to remove all the temporary file in the temp folder.

Before we start let's discuss what will be doing in this article:-

  1. First of all set up the working environment make the working directory and install the required packages.
  2. In second step you will be working on creating the root page(index.html) which will contain text area for code and input where you will write your code and give input respectively in your choice of programming language.
  3. In third step we will start the work on our main file app.js which will define all the functionality of our online compiler.
  4. At last we will define a function to delete the temporary files that were created in the server during compiling program but it's a optional step if you don't want to clear the memory everytime rather than manually deleting them.

1=>Set up the environment for the Application.

First make a directory where all your files and folders will reside.
Go to terminal or cmd write the following commands

mkdir online_compiler
cd online_compiler
npm init //choose defaults
code .   // open visual studio code

Now,what these commands will do is set up your project and will open visual studio code.

2=>Install the required packages

Now install the following packages/modules that will be required for the web-applicaiton

npm install express --save
npm install body-parser --save
npm install compilex --save

Let's us try to understand what these packages will be used for:-
1-> Express will be used for routing pages and creating the server where the web application will run.
2-> Body-parser To handle HTTP POST request in Express.js version 4 and above, you need to install middleware module called body-parser.Body-parser extract the entire body portion of an incoming request stream and exposes it on req.body.The middleware was a part of Express.js earlier but now you have to install it separately.This body-parser module parses the JSON, buffer, string and URL encoded data submitted using HTTP POST request..
3-> Compilex is a npm package which contains all the predefined functionality to create a compiler for several langauage which can be accessed using express GET and POST functions.

After installation of these packages/modules the package.json should look like this:

{
  "name": "online_compiler",
  "version": "1.0.0",
  "description": "",
  "main": "app.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "body-parser": "^1.19.0",
    "compilex": "^0.7.4",
    "express": "^4.17.1"
  }
}

->Let's code

3=>Create the root page

Now, make a html file which will serve as our root page you can name it index.html or anything you like but make the required changes in the app.js file.
What we will do in index.html is that we will define a form which will contain textarea for writing code and input,options menu ,radio buttons for input or not respectively and submit button for result.
index.html shoul look like this:-

<html>
<head>
	<title>Online IDE</title>
</head>
<body>
<center>
<h1>Online IDE</h1>
<form id="myform" name="myform" method="post" action="compilecode">
<h3>Code</h3>
<textarea rows="13" cols="100" id="code" name="code" ></textarea> 
<br/>
<h3>Input</h3>
<textarea rows="10" cols="100" id="input" name="input" ></textarea> 
<br/>
Language : <select name="lang">
  <option value="C">C</option>
  <option value="Java">Java</option>  
  <option value="Python">Python</option> 
</select>
Compile With Input : 
<input type="radio" name="inputRadio" id="inputRadio" value="true"/>yes
<input type="radio" name="inputRadio" id="inputRadio" value="false"/>No
<br />
<input type="submit" value="submit"  name="submit" />
</form>
</center>
</body>
</html>
Here's a screenshot of the html page

Screenshot-from-2020-04-07-11-47-07

4=>Create app.js file

Now create a app.js file which will be the main page but make sure that it should be of the same name as that of the "main" in the package.json file which you should have defined during npm init process.

In the app.js first of all include all the packages and modules that you will use.It can be done using require keyword as shown below:-

var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');
var compiler = require('compilex');

After the inclusion of all the packages in the app.js file we will will use these packages along with other node packages to link all the pages and try to run the web application.
Now, let's create a app variable for using express packages and body-parser

var app = express();
app.use(bodyParser());

Then initialize comiler options from compilex package and link "/" root page with the "index.html".

var option = {stats : true};
compiler.init(option);
app.get('/' , function (req , res ) {
	res.sendfile( __dirname + "/index.html");
});

And define the post funtion for the language you want your compiler to have and with input or without input options.

app.post('/compilecode' , function (req , res ) {
    
	var code = req.body.code;	
	var input = req.body.input;
    var inputRadio = req.body.inputRadio;
    var lang = req.body.lang;
    if((lang === "C") || (lang === "C++"))
    {        
        if(inputRadio === "true")
        {    
        	var envData = { OS : "linux" , cmd : "gcc"};	   	
        	compiler.compileCPPWithInput(envData , code ,input , function (data) {
        		if(data.error)
        		{
        			res.send(data.error);    		
        		}
        		else
        		{
        			res.send(data.output);
        		}
        	});
	   }
	   else
	   {
	   	
	   	var envData = { OS : "linux" , cmd : "gcc"};	   
        	compiler.compileCPP(envData , code , function (data) {
        	if(data.error)
        	{
        		res.send(data.error);
        	}    	
        	else
        	{
        		res.send(data.output);
        	}
    
            });
	   }
    }
    if( lang === "Python")
    {
        if(inputRadio === "true")
        {
            var envData = { OS : "linux"};
            compiler.compilePythonWithInput(envData , code , input , function(data){
                res.send(data);
            });            
        }
        else
        {
            var envData = { OS : "linux"};
            compiler.compilePython(envData , code , function(data){
                res.send(data);
            });
        }
    }

});

then last and final step set the port for the server to listen and and define the get function to send the output data generated after the executed code to the server.

app.get('/fullStat' , function(req , res ){
    compiler.fullStat(function(data){
        res.send(data);
    });
});

app.listen(8080);

One more thing the online compiler will create a temp which will contain all the temporary files created during the process but to clean the memory and remove these files after their use let us define another function for that.

compiler.flush(function(){
    console.log('All temporary files flushed !'); 
    }); 

This will flush all the temporary files.

5=> Summary

Now what's happening here is that when you write your code in the code section and seleect the langauage of your code and also set input button if there is any and submit your code and get the output.
That's it now run your program.

node app.js

This will run your application.

Screenshot of the running application

Screenshot-from-2020-04-07-12-25-01

Screemshot of the output

Screenshot-from-2020-04-07-12-25-11

With this article at OpenGenus, you must have the complete idea of building an online compiler application using Node.JS. Enjoy.

Online Compiler in Node.JS
Share this