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();
});
});
Related
I have this node.js server. The problem is sometimes I notice that it gets stuck. That is the client can make requests, but the server doesn't respond, rather it doesn't end the response, it just gets stuck in the server side. If I look in client side dev tools on the http request, it has a gray circle icon meaning waiting for server response. Even if I wait 10 minutes, nothing happens.
The server side also writes things to console on the requests, which doesn't happen when it gets stuck.
On the node.js console, if I then press ctrl+c when it got stuck, I then suddenly see all the console.log messages just appear on the console, and at the same time, the dev tools, recieves all the responses from the server side, i.e. the gray circle changes to green.
Does anyone know what this problem is?
Thanks
var express = require('express');
var https = require("https");
var fse = require("fs-extra");
var bodyParser = require('body-parser');
// INFO
var root = __dirname + '/public';
setUpServer();
// SET UP SERVER
function setUpServer() {
var app = express();
app.use(express.static(root));
app.use(bodyParser.urlencoded({ extended: false }))
app.get('/', function (req, res) {
var dest = 'index.html';
res.sendFile(dest, { root: root + "/pong" });
});
app.post('/get_brain', function (req, res) {
res.end("1");
console.log('Sent master brain to a client!');
});
app.post('/train_and_get_brain', function (req, res) {
res.end("1");
console.log('Sent master brain to a client!');
});
var privateKey = fse.readFileSync('sslcert/key.pem', 'utf8');
var certificate = fse.readFileSync('sslcert/cert.pem', 'utf8');
var credentials = {key: privateKey, cert: certificate};
var httpsServer = https.createServer(credentials, app);
httpsServer.listen(process.env.PORT || 3000, function () {
var host = httpsServer.address().address;
var port = httpsServer.address().port;
console.log('AI started at https://%s:%s', host, port);
});
}
I'm relative new to NODEJS and I'm struggling with a basic problem, which is the correct use of global variables, I read a lot about it but it seems I can't make it work properly, I'll post some codes for a better view of the problem.
I have this simple js running as a server:
myapi.js
var http = require('http');
var express = require('express');
var app = express();
var exec = require('child_process').exec, child;
var fs = require('fs');
var jUptime;
var ipExp = require('./getDown');
var filesD = [];
var path = "/media/pi/01D16F03D7563070/movies";
app.use(express['static'](__dirname ));
exec("sudo /sbin/ifconfig eth0 | grep 'inet addr:' | cut -d: -f2 | awk '{print $1}'", function(error, stdout, stderr){
ip = stdout;
exports.ipAdd = ip;
console.log(ip);
});
app.get('/files', function(req, res) {
fs.readdir(path, function(err, files) {
if (err){
console.log("Non riesco a leggere i files");
}
filesD=files;
console.log(filesD);
});
res.status(200).send(filesD);
});
app.get('/up', function(req, res) {
child = exec("uptime -p", function(error, stdout, stderr){
jUptime = [{uptime: stdout}];
});
res.status(200).send(jUptime);
});
app.get('*', function(req, res) {
res.status(404).send('Richiesta non riconosciuta');
});
app.use(function(err, req, res, next) {
if (req.xhr) {
res.status(500).send('Qualcosa รจ andato storto');
} else {
next(err);
}
});
app.listen(3000);
console.log('Server attivo sulla porta 3000');
And then I have this JS used in a simple web page:
getDown.js
var ip = require('./myapi').ipAdd;
function gDownloads() {
var url;
var jqxhr;
var dat;
url = 'http://' + ip + '/files';
jqxhr = $.getJSON(url, function(dat) {
for(i=0; i<dat.length; i++){
$('#downLoad').append('<p>' + dat[i] + '</p>');
}
$('#bId').append(dat.length);
})
.done(function() {
console.log("OK");
})
.fail(function(data) {
console.log("Fallito: "+data);
})
};
The problem is that when I navigate to the html page that use getDown.js I get the following error on getDown.js
require is not defined
I need to pass the variable that contains the IP address in myapi.js to use it in getDown.js, I hope I explain myself good enough, thanks in advance.
require is global that exists in Node.js code, that is, on the javascript code executing in the server.
Your server will respond to the client and give it an HTML page to render. That HTML page could tell the browser to also request a javascript file from the server. When it receives that file, the client will execute it. The client does not have a require global (you can test it by opening up the console and typing require)
Using Browserify
Or you can write Node-style code, requiring your global like you're doing, but then run the code through browserify. This will create a new javascript bundle that can be executed by the client, so you should tell your html page to use that bundle instead of getDown.js.
Here is a basic example of doing using browserify like this.
module.js
function getIp() {
return 123456;
}
module.exports = {
getIp: getIp
};
main.js
var module = require('./module');
function getIp() {
var ip = module.getIp();
return ip;
};
console.log(getIp());
compile bundle
$ browserify main.js -o public/bundle.js
index.html
<script type="text/javascript" src="public/bundle.js"></script>
Global variable on the client
To use a global variable on the client which is known by the server, you can pass that variable to your rendering engine (possibly Jade if you're using Express) and have it interpolate that variable into a <script> tag which defines some globals. Leave a comment if that's the approach you'd prefer and I can add some more details.
Let me know if you have more questions!
i have a main file -- index.js:
var express = require('express');
var app = express();
var request = require('request');
var demo = require('demo');
// This app will only respond requests to the '/scrape' URL at port 3000.
app.get('/scrape', function (req, res) {
var url = "http://www.l.com";
request(url, function (error, response, html) { // two parameters: an URL and a callback
if (!error) {
demo(html);
}
});
});
var server = app.listen(3000, function () {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});
and my module is demo.js:
module.exports = function (html) {
....
return JSON.stringify(json);
}
The error is :
TypeError: demo is not a function
I am new to node.js, i would like to know why this didn't work. Maybe i dont understand the real principle of module?
Thank you for answer me first.
You're not exporting your module properly. It should be:
exports.demo = function ....
Try to include your demo module in index.js:
var demo = require('./demo.js');
For the other freshers who use module in node.js for the first time.
first, made a new module called the name of your module.js
Second, it is not necessary to do "
npm install demo --save", if you want, it is also okay.
Third, in the main js which u want to call this module, focus on the name and the path of the module, you should write var anyName = require('the name of your module');, if they are in the same directory, you should write like this: var anyName = require('./the name of your module');
I really hope to find some answers here as i tried everything by now.
Background:
Overtime we deploy code to web server, we need to do a cache warm up, i.e. access the site and make sure it loads. First load is always the slowest since IIS require to do some manipulations with a new code and cache it.
Task:
Create a page which will a checkbox and a button. Once button is pressed, array of links sent to server. Server visits each link and provides a feedback on time it took to load each page to the user.
Solution:
I am using node JS & express JS on server side. So far i manage to POST array to the server with links, but since i have limited experience with node JS, i can not figure out server side code to work.
Here is a code i got so far (it is bits and pieces, but it gives an idea of my progress). Any help will be greatly appreciated!!!
var express = require("express");
var app = express();
var bodyParser = require('body-parser');
var parseUrlencoded = bodyParser.urlencoded({ extended: false});
var http = require("http");
function siteToPrime(url){
http.get(url, function (http_res) {
// initialize the container for our data
var data = "";
// this event fires many times, each time collecting another piece of the response
http_res.on("data", function (chunk) {
// append this chunk to our growing `data` var
data += chunk;
});
// this event fires *one* time, after all the `data` events/chunks have been gathered
http_res.on("end", function () {
// you can use res.send instead of console.log to output via express
console.log(data);
});
});
};
//Tells express where to look for static content
app.use(express.static('public'));
app.post('/', parseUrlencoded, function(request, response){
var newBlock = request.body;
console.log(Object.keys(newBlock).length);
var key = Object.keys(newBlock)[0];
console.log(newBlock[key]);
siteToPrime("www.google.com");
response.status(201);
});
app.listen(3000, function(){
console.log("Server listening on port 3000...");
});
Assuming that you have access to the array in the post route:
var express = require("express"),
request = require("request"),
app = express();
var start = new Date();
app.use(express.static('public'));
app.use(bodyParser.urlencoded({extended: false}));
function siteToPrime(req, res, urls) {
urls.forEach(function(url)) {
request(url, function(error, res, body) {
if (!error && res.statusCode == 200) {
console.log(url +' : ' + body);
console.log('Request took: ', new Date() - start, 'ms');
}
});
}
res.redirect('/');
};
app.post('/', function(req, res){
var urls = req.body.urls // Array os urls.
siteToPrime(req, res, urls);
});
app.listen(3000, function(){
console.log("Server listening on port 3000...");
});
The argument of require(...) in node.js is a filename. If I had a module source code in a string code, could I somehow call require(code) and load functions from that string?
I put this into a function for reuse. It creates a file in the os temp directory based on a random hash, requires it and then deletes it.
var fs = require('fs'),
os = require('os'),
crypto = require('crypto');
function requireString(moduleString) {
var token = crypto.randomBytes(20).toString('hex'),
filename = os.tmpdir() + '/' + token + '.js',
requiredModule = false;
// write, require, delete
fs.writeFileSync(filename, moduleString);
requiredModule = require(filename);
fs.unlinkSync(filename);
return requiredModule;
}
Then you can do:
var carString = "exports.start = function(){ console.log('start'); };",
car = requireString(carString);
console.log("Car:", car);
This is still more of a workaround, but more convenient to use, I think.
A work around could be to write the module source code to a temporary file ./tmp-file.js and then require('./tmp-file'), and then remove the file.
This is probably not optimal because you would either have to block and write the file synchronously, or put everything requiring that module in the callback to the async write.
A working example for async file write (gist - also includes sync file write):
var http = require('http');
var fs = require('fs');
var helloModuleString = "exports.world = function() { return 'Hello World\\n'; }";
fs.writeFile('./hello.js', helloModuleString, function (err) {
if (err) return console.log(err);
var hello = require('./hello');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end(hello.world());
}).listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');
});
Results in:
$ curl 127.0.0.1:1337
> Hello World