How to replace .js file content based on number of calls - javascript

I do have a site which calls a javascript file located outside of my site. What i want is that it's content gets replaced once every X calls repeadetly.
First i thought i could use Node.js and use a function like this:
var express = require('express');
var app = express();
var path = require('path');
var Chance = require('chance');
var chance = new Chance();
app.get('/get-javascript-file', function(req, res) {
if (chance.integer({min: 1, max: 10}) == 1) {
res.sendFile(path.join(__dirname + '/someFile.js'));
} else {
res.sendFile(path.join(__dirname + '/someOtherFile.js'));
}
});
app.listen(80);
But as you can see the script itself replaces js file with another one. I was hoping i could do somehow the same with just one js file.

Related

Document is not defined on node.js - How can i import a variable from another .js file to node.js server?

Edit: Actually, my problem is "How to use "value" from selection.js in the server.js ? " I want to direct user to a searching page according to his/her choice .
i am new at web programming. I have server.js and a selection.js.
server.js is a node file, and my server is in it. selection.js is my item class changer. I am changing selected item's class with selection.js and i am trying to use this selected item from server.js. When i try below codes, i am taking this shit: Document is not defined on node.js
It is really painful. I am trying to solve it about hours. But, nothing!
Pls, help me :/
selection.js :
var iconContainer = document.getElementById('iconContainer');
var icon = iconContainer.getElementsByClassName("item");
for (var i = 0; i < icon.length; i++) {
icon[i].addEventListener("click", function() {
var current = document.getElementsByClassName("active");
current[0].className = current[0].className.replace(" active", "");
this.className += " active";
const btnSearch = document.querySelector("#btnSearch");
btnSearch.addEventListener("click", () => {
// get the active item's value
const value = document.querySelector(".item.active span").innerText;
console.log("value: ", value);
// do fetch
});
});
}
module.exports={searchPath: "/"+value};
server.js:
var fs = require('fs');
var express = require('express');
var app = express();
var path = require('path');
app.use('/public', express.static(path.join(__dirname, 'public')));
// '/' girdisi için index.html getirilecek.
app.get('/', function (req, res) {
fs.readFile('index.html', function(err, data) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(data);
res.end();
});
});
//---------------------------------------------------
// Server kuruyoruz.
var server = app.listen(8081,"127.0.0.1", function () {
var host = server.address().address;
var port = server.address().port;
console.log('Server http://' + host + ':' + port+' adresinde çalışıyor...');
});
var search = require('./public/js/selection');
console.log(search.searchPath);
So, the code you label as selection.js needs to be in your web page, either directly embedded or linked from a <script> tag so it can run in the web page in the browser.
Then, that code can make an Ajax call using the XMLHttpRequest or fetch() interfaces in the browser to a route on your server and pass the desired value.
That route on your server (which you need to define and add code for) can then examine that value and decide what data to return the the Ajax call.
Your Javascript in the web page, then receives that returned data from the Ajax call and decides what to do with it such as insert new content in the page for the user to see, cause the browser to load a different page or refresh the current page or whatever else is appropriate.

Trying to run a script with Express on localhost:3000

Stuck on my first attempt at a basic app. Scraper.js scrapes a URL and writes the returned array to the document obj when run alone in console, so that part works. Now all I want is an Express server to run the script whenever I open localhost:3000 but not sure how to do so.
|node_modules
|package.json
|public
|-index.html (boilerplate HTML. Not importing anything)
|src
|-scraper.js
|index.js
index.js:
var scraperjs = require('scraperjs');
var express = require('express');
var app = express()
app.use(express.static(__dirname + '/public'));
app.listen(3000);
--
scraper.js:
scraperjs.StaticScraper.create('https://examplesite.com/')
.scrape(function($) {
return $(".entry-content p").map(function() {
var content = $(this).html();
return content
}
}).get();
})
.then(function(data) {
... // eventually will write the items returned from the data array to div's
}
});
You need to export the scraperjs function using module.exports = functionName() as the last line in scraper.js.
Your require in index.js needs to factor in the path location for scraper.js. So:
var scraperjs = require('./src/scraperjs');
Here is a one that i've coded with promises, and also using a global variable which is daNews
var scraperjs = require('scraperjs');
var express = require('express');
var app = express();
app.use(express.static(__dirname + '/public'));
var url = 'https://news.ycombinator.com/';
var daNews;
function myScraper(){
return new Promise((resolve, reject) => {
scraperjs.StaticScraper.create(url)
.scrape(function($) {
return $(".title a").map(function() {
return $(this).text();
}).get();
})
.then(function(news) {
daNews = news;
resolve('done');
})
});
}
app.get('/', function(req, res){
async function m1(){
var x = await myScraper();
if(x == 'done'){
res.send(daNews);
}else{
console.log('err');
}
}
m1();
})
app.listen(3000);

issue child process inside a server on node.js

I have an executable library in C (sudo ./ads1256_test adc.txt) where data are acquired from an ADC, likewise these data are automatically save in a text file (adc.txt).
On the other hand, I have a server in node.js (see code) in which would like to execute this program when a button in the website is pressed. For this, I tried to implement this process using the child process .exec('sudo ./ads1256_test adc.txt') but it did not work. It apparently runs but the values saved in the file are always zero. That is totally different to the obtained result when I execute the same command in terminal. I would appreciate if anybody could help me.
//Importing the core modules
var express = require('express');
var path = require('path');
var sys = require('sys');
var fs = require('fs');
var util = require('util');
var sleep = require('sleep');
var app = express();
var exec = require('child_process').exec;
var spawn = require('child_process').spawn;
app.get('/', function(req,res){
res.sendFile(path.join(__dirname + '/public/index.html'));
});
//Static Directories
app.use(express.static(__dirname + '/public'));
app.post('/test', function (req, res) {
exec('sudo ./ads1256_test adc.txt');
});
//Server Starting
var server = app.listen(8080, function(err){
if(err){
console.log('Error starting http server');
} else{
console.log('Sever running at http://localhost:8080 ');
}
});
first thing first, fix your code to
- asynchronously handle the cp spawn
- show errors
Example with tree, may you adapt it to your binary and check the response, it should help you go forward.
app.post('/test', function (req, res) {
var cp = spawn('tree', []);
cp.stdout.pipe(res);
cp.stderr.pipe(res);
cp.on('close', function () {
res.end();
cp.stdout.unpipe();
cp.stderr.unpipe();
});
});

Run the script in node.js only after user select file in html

I am using node.js to launch a serve so that my html can communicate with R code. But I am facing a problem on node.js. In my html page, I have a browse selection button, user can use it to choose the data file they want to read into html and node.js will pass the file name to R, so R code will read data from the selected data file and then run the analytics model. But as i only have very basic knowledge of Node.js, so currently, r code would run only when I open the followling link "localhost:3000/vis/rio". So my question is how to make node.js run the R code in background automatically when the data file has been selected. Thank you very much for your help in advance.
Here are my codes:
Javascript-(sending the file name to node.js):
var dataset,availableTags;
function handleFileSelect(evt) {
var file = evt.target.files[0];
$.ajax({ //getting the file name and update to node.js
type:'post',
url:"/getFileName",
data:{filename:file.name}
});
Papa.parse(file, { //papa is a library I used to read csv file
header: true,
dynamicTyping: true,
complete: function(results) {
dataset=results.data;
}
});
}
$(document).ready(function(){
$("#csv-file").change(handleFileSelect);
});
Node.js script:
serve.js:
var express=require('express');
var path = require('path');
var vis = require('./routes/vis');
var index = require('./routes/index');
var bodyParser=require('body-parser');
var app=express();
require('./routes/main')(app);
app.get('/vis/rio',vis.rio); **//this is a package used to get connection with Rserve**
app.set('views',__dirname + '/views');
app.set('view engine', 'ejs');
app.engine('html', require('ejs').renderFile);
app.use(express.static(path.join(__dirname, 'public')));
app.use(bodyParser.urlencoded());
app.post("/getFileName",index.getFileName); **//this is the script to get the file name, it is from index.js**
var server=app.listen(3000,function(){
console.log("Express is running on port 3000");
});
index.js // this is the js file for getting file name
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res) {
res.render('index', { title: 'Express' });
});
getFileName=function (req,res){
global.filename=req.body.filename; **//this is the global variable which stores the file name**
res.send('true');
};
module.exports = {router:router,getFileName:getFileName};
vis.js // this is the file used to connect with Rserve and pass the name to R code
var rio = require("rio");
var arg={};
exports.rio = function(req, res){
arg={names:[global.filename]};
console.log(arg);
options = {
entryPoint:"nameoffile",
data: arg,
host : "127.0.0.1",
port : 6311,
callback: function (err, val) {
if (!err) {
console.log("RETURN:"+val);
return res.send({'success':true,'res':val});
} else {
console.log("ERROR:Rserve call failed")
return res.send({'success':false});
}
},
}
rio.enableDebug(true);
rio.sourceAndEval(__dirname + "/Rcode/test.R",options);
};
It looks like you aren't calling out to /vis/rio at any point when you make the call out to your server.
You'll either need to make a second call on the client side to /vis/rio or if you want to use that section, you can import/require the module in index.js and include it in getFileName and just call out to the function there before you return the file. I'm not super familiar with rio, but I don't see any access point in your code to that function.
Edit: If I understand what you're trying to do correctly, you can always make a second request (to /vis/rio) in the success callback of your first ajax call.

Express.js and form validation

I'm tring to create a simple node- with express.js script that will sum 3 numbers.
On index I have this:
index.jade
!!! 5
html
head
title Test
body
form(name='form1', method='post', action='/')
label(for='1')
input#1(type='text', name='1')
label(for='2')
input#2(type='text', name='2')
label(for='3')
input#3(type='text', name='3')
input(name='submit', type='button', value='submit')
#result
and also i'm now writing the serverside - app.js with req and res object but how to return a result... also result = 1id + 2id + 3id
app.js
var express = require('express');
app = express.createServer();
app.use(express.bodyParser());
app.post('/', function(req, res){
var i = req.param('1', null);
var j = req.param('2', null);
var k = req.param('3', null);
var r = i+j+k;
res.send(r);
});
How I to send results (r) into div id Result on index.jade... so how to return result to index.jade
also here is pastebin code: http://pastebin.com/J9MRFCaE ... i'm new to node and express and sorry for stupid question...
It's simple, just call your "index.jade" rendering passing your data (instead of 'res.send(r);') :
res.render('index', {
result: r
});
And display "result" variable in your jade file :
#result #{result}
Additional information on jade code and express rendering

Categories