Online compiler with node.js - node.js

I am trying to build an online compiler IDE and I always get an error that I can't understand or solve. the project/application consists of (index.html - package.json - app.js) the "app.js" refers to the server side which surely causes this error ("File not found: Firefox can’t find the file at /C:/Users/Mr_Tech/Desktop/online_judge_system/compilecode"). this is the code:
// including all packages and modules that will be used
var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');
var compiler = require('compilex');
// create a app variable for using express packages and body-parser
var app = express();
//app.use(bodyParser());
app.use(express.urlencoded({ extended: true }))
//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");
});
// 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 : "windows" , cmd : "g++"};
compiler.compileCPPWithInput(envData , code ,input , function (data) {
if(data.error)
{
res.send(data.error);
}
else
{
res.send(data.output);
}
});
}
else
{
var envData = { OS : "windows" , cmd : "g++"};
compiler.compileCPP(envData , code , function (data) {
if(data.error)
{
res.send(data.error);
}
else
{
res.send(data.output);
}
});
}
}
if(lang === "Java")
{
if(inputRadio === "true")
{
var envData = { OS : "windows" };
console.log(code);
compiler.compileJavaWithInput( envData , code , function(data){
res.send(data);
});
}
else
{
var envData = { OS : "windows" };
console.log(code);
compiler.compileJavaWithInput( envData , code , input , function(data){
res.send(data);
});
}
}
if( lang === "Python")
{
if(inputRadio === "true")
{
var envData = { OS : "windows"};
compiler.compilePythonWithInput(envData , code , input , function(data){
res.send(data);
});
}
else
{
var envData = { OS : "windows"};
compiler.compilePython(envData , code , function(data){
res.send(data);
});
}
}
}); // end POST function
// 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(8000);
// function to delete all the temporary files created during the process
compiler.flush(function(){
console.log('All temporary files flushed !');
});

Nope. The problem is you are using a file:// path when this needs to be run as a HTTP server and you need to go to localhost:8000. You also used a backslash as a web path which is invalid.

Related

Why is the request handler called continuously (like every second) in node?

I've got this (complete code – well, sort of):
const fs = require('fs');
const http = require('http');
const url = require('url');
const path = require('path');
const Handlebars = require('handlebars');
const Router = require('./router');
const Utils = require('./utils');
const utils = new Utils();
const views = require('./views');
let hostname,
server,
router = new Router();
const port = ( process.argv.length > 2 ) ? parseInt(process.argv[process.argv.length - 1]) : 3000;
function install ( config ) {
let install_processes = [
installControllers( config ),
installModels( config ),
views( config )
];
return Promise.all( install_processes );
}
function installControllers ( config ) {
// To keep example compact, this return a Promise
}
function installModels ( config ) {
// To keep example compact, this return a Promise
}
function handleRequest ( req, res ) {
let r = global.routes.find( ( obj ) => obj.route === req.url );
if ( r ) {
let template = global.routes.views.layout,
output = template( req.body );
r.action();
res.statusCode = 200;
res.setHeader('Content-Type', 'text/html');
res.end( output );
} else {
res.statusCode = 404;
res.setHeader('Content-Type', 'text/plain');
res.end("404: page not found, " + req.url);
}
}
var fw = (function ( ƒ ) {
ƒ.init = function Init ( config ) {
config = config;
hostname = config.hostname ? config.hostname : '127.0.0.1';
install( config )
.then(function () {
ƒ.startServer();
})
.catch(function ( err ) {
console.error("Error", err);
})
}
ƒ.startServer = function () {
server = http.createServer( handleRequest ).listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}`);
});
}
return ƒ;
}( fw || {} ));
module.exports = fw;
Please note, that variables and handlers are set elsewhere.
Everything works fine. But why is the handleRequest handler called every second (without any incoming requests. And it's actually called TWICE within that second)? If I add a console.log it gets output every second or so.
I would expect it to be called ONLY when actual requests are made to the server. Is this some sort of timeout handler that runs in the background or the like?
Why is handle triggered twice when starting the server, that is?
Try adding this to a file (wtf.js) and run: node wtf 9000;
```
const http = require('http');
function handle ( req, res ) {
console.log("Handling request");
}
var fw = (function () {
http.createServer( handle ).listen(9000, '127.0.0.1', () => {
console.log("Server running");
});
}());
module.exports = fw;
```
And actually, while writing this post I can see in the console, that it gets triggered again ... minutes later. Something spooky is going in here.
In case you run into the same 'situation':
Normally working in FireFox. At some point I had opened Chrome to use the debugger, and forgot all about it. THAT was the bugger continuously sending requests in the background ... sigh! Yes, web dev IS hard.
So check all possible incoming channels ; )

Unexpected token require('https’)?

I am new to node js. I am a bit struggling to fix this compilation issue.
How do I fix this? I believe I am missing some package. How can I include it?
I get error on the line require('https') i.e unexpected token. I have tried running npm install https -g but it hasn't fixed anything. I am running this code on Ubuntu and OSX.
var https = require('https’);
const parseUrl = require('parseurl');
var options = {
key: fs.readFileSync(‘/Users/admin/Dropbox/node_prj/SiteNodeJS/server.key’),
cert: fs.readFileSync(‘/Users/admin/Dropbox/node_prj/SiteNodeJS/server.crt’)
};
const fileEngine = require('./fileErrHandler');
const UrlLoader = require('./urlController');
https.createServer(options, function (req, res)
{
try
{
// this is a library function
var pathName = decodeURIComponent(req.url);
var pathCheck = fileEngine(pathName); //return true or error message
if(pathCheck){
}
else{
}
var fileResEngine= new fileEngine(pathName);
// create a literal validateFile to validate the path
fileResEngine.pathCheck();
if (fileResEngine.error === true )
{
res.statusCode = fileResEngine.statusCode;
res.end(fileResEngine.ErrorMsg);
return;
}
else
{
var UrlResLoader = new UrlLoader();
UrlResLoader.requestUrl(fileResEngine, function(urctrl){
res.writeHead(urctrl.httpcode, urctrl.fileType);
res.write(urctrl.data);
res.end();
});
}
}
catch(err)
{
res.statusCode = err.status || 500;
res.end(err.message);
}
}).listen(443);
It seems you have a typo here: var https = require('https’ <---); You have a tick instead of a single quote.

node.js - page keeps loading - no errors to investigate

this is 1.js
let's run it
node 1.js
and then on the web
execute: domain.tld/-2
it all works perfect.
i see it loaded 2.js and then
used a function to do the mysql query
and displays all the results. perfect.
now on the web let's try to
go to : domain.tld/-3
1.js tries to load 3.js
because the urlpath name is '/-3'
but there is no '3.js'
i am expecting it to say
"page not found'
node 1.js is not crashing.
and web browser is still.. 'loading.."
here is the 1.js :
var http = require('http');
var url = require('url');
var mysql = require('mysql');
var Memcached = require('memcached');
var memcached = new Memcached('localhost:11211');
var connection = mysql.createConnection({
host : '--------------',
user : '2',
password : '-------------',
database : '1'
});
connection.connect();
var server=http.createServer(function(req,res){
res.writeHead(200,{'Content-Type': 'text/html; charset=utf-8'});
var pathname=url.parse(req.url).pathname;
if (pathname.match(/\/-\d{1,2}/)) {
pathname = pathname.replace('-', '')
try{
var o = require('/' + pathname + '.js')
} catch (err){
var o = '0'
}
if (o == '0'){
o = 'page not found'
}else{
o.makeQuery(connection, function(err, result){
if(err) return res.end(err);
o = result;
res.end(o)
});
}
} else if (pathname.match(/^\/$/)) {
res.end('welcome to index page');
} else {
pathname = pathname.replace('/', 'o');
res.end('welcome to user profile page');
}
}).listen(80);
although it may not matter..
here is the 2.js
exports.makeQuery = function(connection, callback) {
var queryString = 'SELECT * FROM 1_accounts order by ac_nu asc limit 5';
connection.query(queryString, function(err,res,fields){
if (err) {return callback(err)};
bb = JSON.stringify(res);
callback(null, bb);
});
}
before i added the following segment to
1.js it was working fine via web.
if (pathname.match(/\/-\d{1,2}/)) {
} else if (pathname.match(/^\/$/)) {
} else {
}
in other words it must have something to do
with those perhaps.
before i added those lines..
it would smoothly display:
"page not found"
You have set o='page not found' but there is no response.write(o) or res.end(o) for it as it is in the else part hence it will never be displayed

Having Difficulties in Integrating a Simple Code Snippet into a Complex Existing Node.js Code

I am trying to add a new URL path (Node.js home page has given an example to do it.) to a piece of complex existing code (shown below). The existing code already has server configuration code but the code looks very different from the "Building a Node.js Web Server" example that is showing in the Node.js home page.
The new URL path is "/lens/v1/ping" that is sent from the browser window.
If that is the URL path received, I am supposed to send a response Status 200 back to the browser.
I am having difficulties to fit this new URL path and its associated code to the existing code (show below) and I am seeking help. Thank you very much.
/**
* Entry point for the RESTFul Service.
*/
var express = require('express')
var config = require('config');
var _ = require('underscore');
var bodyParser = require("vcommons").bodyParser;
// Export config, so that it can be used anywhere
module.exports.config = config;
var Log = require('vcommons').log;
var logger = Log.getLogger('SUBSCRIBE', config.log);
var http = require("http");
var https = require("https");
var fs = require("fs");
var cluster = require("cluster");
var numCPUs = require('os').cpus().length;
if (cluster.isMaster) {
// Fork workers.
for (var i = 0; i < numCPUs; i++) {
cluster.fork();
}
cluster.on('online', function (worker) {
logger.info('A worker with #' + worker.id);
});
cluster.on('listening', function (worker, address) {
logger.info('A worker is now connected to ' + address.address + ':' + address.port);
});
cluster.on('exit', function (worker, code, signal) {
logger.info('worker ' + worker.process.pid + ' died');
});
} else {
logger.info("Starting Subscription Application");
createApp();
}
// Create Express App
function createApp() {
var app = express();
app.configure(function () {
// enable web server logging; pipe those log messages through winston
var winstonStream = {
write : function (message, encoding) {
logger.trace(message);
}
}; // Log
app.use(bodyParser({}));
app.use(app.router);
if (config.debug) {
app.use(express.errorHandler({
showStack : true,
dumpExceptions : true
}));
}
});
// Include Router
var router = require('../lib/router')();
// Subscribe to changes by certain domain for a person
app.post('/lens/v1/:assigningAuthority/:identifier/*', router.submitRequest);
// Listen
if (!_.isUndefined(config.server) || !_.isUndefined(config.secureServer)) {
if (!_.isUndefined(config.server)) {
http.createServer(app).listen(config.server.port, config.server.host, function () {
logger.info("Subscribe server listening at http://" + config.server.host + ":"
+ config.server.port);
});
}
if (!_.isUndefined(config.secureServer)) {
https.createServer(fixOptions(config.secureServer.options), app).listen
(config.secureServer.port, config.secureServer.host, function () {
logger.info("Subscribe server listening at https://" + config.secureServer.host
+ ":" + config.secureServer.port);
});
}
} else {
logger.error("Configuration must contain a server or secureServer.");
process.exit();
}
}
function fixOptions(configOptions) {
var options = {};
if (!_.isUndefined(configOptions.key) && _.isString(configOptions.key)) {
options.key = fs.readFileSync(configOptions.key);
}
if (!_.isUndefined(configOptions.cert) && _.isString(configOptions.cert)) {
options.cert = fs.readFileSync(configOptions.cert);
}
if (!_.isUndefined(configOptions.pfx) && _.isString(configOptions.pfx)) {
options.pfx = fs.readFileSync(configOptions.pfx);
}
return options;
}
// Default exception handler
process.on('uncaughtException', function (err) {
logger.error('Caught exception: ' + err);
process.exit()
});
// Ctrl-C Shutdown
process.on('SIGINT', function () {
logger.info("Shutting down from SIGINT (Crtl-C)")
process.exit()
})
// Default exception handler
process.on('exit', function (err) {
logger.info('Exiting.. Error:', err);
});
A browser window executes a HTTP GET request. After the // Include Router call, that is where you would define your express GET function.
...
// Include Router
var router = require('../lib/router')();
//*********
//define your method here, as shown, or in your router file.
app.get('lens/v1/ping', function(req, res){
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end();
} );
//*********
// Subscribe to changes by certain domain for a person
app.post('/lens/v1/:assigningAuthority/:identifier/*', router.submitRequest);
...

regarding foodme project in github

hello i have a question regarding the foodme express example over github:
code:
var express = require('express');
var fs = require('fs');
var open = require('open');
var RestaurantRecord = require('./model').Restaurant;
var MemoryStorage = require('./storage').Memory;
var API_URL = '/api/restaurant';
var API_URL_ID = API_URL + '/:id';
var API_URL_ORDER = '/api/order';
var removeMenuItems = function(restaurant) {
var clone = {};
Object.getOwnPropertyNames(restaurant).forEach(function(key) {
if (key !== 'menuItems') {
clone[key] = restaurant[key];
}
});
return clone;
};
exports.start = function(PORT, STATIC_DIR, DATA_FILE, TEST_DIR) {
var app = express();
var storage = new MemoryStorage();
// log requests
app.use(express.logger('dev'));
// serve static files for demo client
app.use(express.static(STATIC_DIR));
// parse body into req.body
app.use(express.bodyParser());
// API
app.get(API_URL, function(req, res, next) {
res.send(200, storage.getAll().map(removeMenuItems));
});
i don't understand where is the api folder. it doesn't exist and i don't understand how information is going in and out from there. i can't find it.
can someone please explain this to me?
another question:
there is a resource for the restaurant
foodMeApp.factory('Restaurant', function($resource) {
return $resource('/api/restaurant/:id', {id: '#id'});
});
and in the restaurant controller there is a query:
var allRestaurants = Restaurant.query(filterAndSortRestaurants);
and the following lines:
$scope.$watch('filter', filterAndSortRestaurants, true);
function filterAndSortRestaurants() {
$scope.restaurants = [];
// filter
angular.forEach(allRestaurants, function(item, key) {
if (filter.price && filter.price !== item.price) {
return;
}
if (filter.rating && filter.rating !== item.rating) {
return;
}
if (filter.cuisine.length && filter.cuisine.indexOf(item.cuisine) === -1) {
return;
}
$scope.restaurants.push(item);
});
// sort
$scope.restaurants.sort(function(a, b) {
if (a[filter.sortBy] > b[filter.sortBy]) {
return filter.sortAsc ? 1 : -1;
}
if (a[filter.sortBy] < b[filter.sortBy]) {
return filter.sortAsc ? -1 : 1;
}
return 0;
});
};
the things that isn't clear to me is:
how is that we are giving the query just a function without even activating it.
as i understand we should have passed the query somthing like:
{id: $routeParams.restaurantId}
but we only passed a reference to a function. that doesn't make any sense.
could someone elaborate on this?
thanks again.
var API_URL = '/api/restaurant';
var API_URL_ID = API_URL + '/:id';
var API_URL_ORDER = '/api/order';
These lines are just defining string constants that are plugged into Express further down. They're not a folder.
app.get(API_URL, function(req, res, next) {
res.send(200, storage.getAll().map(removeMenuItems));
});
So this function call to app.get(API_URL... is telling Express "Look out for GET requests that are pointed at the URL (your app's domain)/api/restaurant, and execute this function to handle such a request."
"api" is not a folder.
Every requests will pass through the app.get method.
This method will respond to the routes /api/restaurant as defined in the API_URL variable.

Resources