Unexpected token require('https’)? - node.js

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.

Related

Modified Req Url in Express middleware ERR_HTTP_HEADERS_SENT: Cannot set headers after they are sent to the client

Hey guys I am facing the error Error "[ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client" when I am trying to modify the req.url in a express middleware.
My middleware
export function ModifyQueryMiddleware(config, Authconfig, Repo ){
const accessTokenMap = new Map();
return async (request, res, next) => {
const accessToken = request.header('authorization') as string;
if(!accessToken){
throw new HttpException(res, 403)
}
if(!accessTokenMap.get(accessToken)){
const JWKS = jose.createRemoteJWKSet(new URL(config.jkwsUri));
try {
const jwtVerifyResult = await jose.jwtVerify(accessToken.replace('Bearer ', ''), JWKS);
const {payload} = jwtVerifyResult;
accessTokenMap.set(accessToken, payload)
const aumParams = await authentication(payload, authConfig,Repo);
const queryRestrictionStrategy = QueryRestrictionStrategyFactory(aumParams, request)
queryBuilder(queryRestrictionStrategy)
next()
} catch(err){
}
}
const payload = accessTokenMap.get(accessToken);
const aumParams = await authentication(payload, authConfig, repo);
const queryRestrictionStrategy = QueryRestrictionStrategyFactory(aumParams, request)
queryBuilder(queryRestrictionStrategy)
next()
}
}
My queryBuilder:
export function queryBuilder(strategy: QueryRestrictionStrategy){
const {req, id} = strategy
if(req.url === '/someurl'){
req.url = `/someurl?${id}`
}
return
}
I am really confused as I don't modify the header of a response instead I am just modifying the query without the querybuilder the middleware works fine. I already looked at a few questions regarding this error however the res was there always modified.
Any help or tips would be really appreciated !
Your code can call next twice when !accessTokenMap.get(accessToken) is true. You have to return once that part of your code is handled:
if (!accessTokenMap.get(accessToken)) {
const JWKS = jose.createRemoteJWKSet(new URL(config.jkwsUri));
try {
...
next();
} catch(err) {
next(err); // make sure to pass the error along!
}
return;
}

Online compiler with 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.

Node js Service Doesnt Return anything

i have a simple code to wait for 10 min in "api/get" endpoint in Node js despite of keeping the both req.setTimeout(9000000); and server.setTimeout(5000000); still neither there is any error nor i am getting any result.It simply gets stuck.
const express = require('express');
const newman = require('newman');
var sleep = require('sleep');
const app = express();
const fs = require('fs');
var request = require("request");
var testexecution = require('./TestStatus');
var uploadtoblob = require('./BlobFiles');
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.get('/api/version',(req,res)=>{
console.log("Started!")
res.status(200).json({
message: 'version 1.1.1'
});
});
app.get('/api/secondEndpoint',(req,res)=>{
console.log("Second Endpoint Started")
request({
uri: "http://protractortestcasesnew.eastus.azurecontainer.io/api/test",
method: "GET",
timeout: 1200000,
followRedirect: true,
maxRedirects: 10
}, function(error, response, body) {
console.log("Second Endpoint Exit")
return res.status(400).json(response.statusMessage);
});
});
app.get('/api/test',(req,res)=>{
req.setTimeout(9000000);
const cp = require('child_process');
var testName=req.rawHeaders[1];
//var enviroment=req.rawHeaders[2];
var enviroment="predev";
var file='/app/TestCases/reports\\testReport.html';
var connectionStringfile='/app/Service/NodejsWebApp/Values.json';
try
{
console.log("Method Entry");
setTimeout(() => { return res.status(200).json({
message: 'Pass'
}); }, 240000);
}
catch (error)
{
if((error.status == 1) && (error.message == "Command failed: npm test") && (fs.existsSync('/app/TestCases/reports\\testReport.html' && '/app/TestCases/reports\\testReport.html.json' )) )
{
console.log("Catch Exit");
console.log("res");
return res.status(404).json({
message: 'Failed npm Error'
});
}
else
{
console.log("Error!");
error.status;
error.message;
error.stderr;
error.stdout;
return res.status(500).json({
message: 'Failed'
});
}
}
});
var server=app.listen(80,()=>console.log("server is up"))
module.exports = app;
server.setTimeout(5000000);
i have a simple code to wait for 10 min in "api/get" endpoint in Node js despite of keeping the both req.setTimeout(9000000); and server.setTimeout(5000000); still neither there is any error nor i am getting any result.It simply gets stuck.
I figured out that after 4 mins or so the httpClient closes and does not give response out.So to overcome it you can probable poll on the endpoint after 2 mins and see if result is available or not and then get the result.

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.

Node.js download multiple files

I need to download multiple files from urls. I have got list of them in the file. How should I do that? I already made it, but it's not working. I need to wain until last download is done before starting next wan. How can I do that?
You want to call the download function from the callback of the file before that. I threw together something, do not consider it pretty nor production ready, please ;-)
var http = require('http-get');
var files = { 'url' : 'local-location', 'repeat-this' : 'as often as you want' };
var MultiLoader = function (files, finalcb) {
var load_next_file = function (files) {
if (Object.keys(files) == 0) {
finalcb(null);
return;
}
var nexturl = Object.keys(files)[0];
var nextfnname = files[nexturl];
console.log('will load ' + nexturl);
http.get(nexturl, nextfnname, function (err, result) {
console.log('loaded ' + nexturl);
delete files[nexturl];
load_next_file(files);
});
};
load_next_file(JSON.parse(JSON.stringify(files)));
};
MultiLoader(files, function () { console.log('finalcb'); });
http-get is not a standard node module, you can install it via npm install http-get.
I think this is what you're looking for.
const fs = require('fs')
const https = require('https')
const downloadFolderPath = 'downloads'
const urls = [
'url 1',
'url 2'
]
const downloadFile = url => {
return new Promise((resolve, reject) => {
const splitUrl = url.split('/')
const filename = splitUrl[splitUrl.length - 1]
const outputPath = `${downloadFolderPath}/${filename}`
const file = fs.createWriteStream(outputPath)
https.get(url, res => {
if (res.statusCode === 200) {
res.pipe(file).on('close', resolve)
} else {
reject(res.statusCode)
}
})
})
}
if (!fs.existsSync(downloadFolderPath)) {
fs.mkdirSync(downloadFolderPath)
}
let downloadedFiles = 0
urls.forEach(async url => {
await downloadFile(url)
downloadedFiles++
console.log(`${downloadedFiles}/${urls.length} downloaded`)
})
You can read files using fs (var fs = require('fs');)in node js
fs.readFile('<filepath>', "utf8", function (err, data) {
if (err) throw err;
console.log(data);
});

Resources