Programming the BeagleBone to turn on LED, Got NodeJS errors - node.js

The assignment is about embedded system. We are learning how to use BeagleBone Black and how we can use it to make small-size devices e.g., devices that can measure temperature and pulse.
A part of our first assignment is to follow this guide: https://randomnerdtutorials.com/programming-the-beaglebone-black-with-bonescript/
We need to make a server in Node JS and a index in html. The site provides button to control a LED light that is connected to a breadboard via BeagleBone Black.
I have connected the LED, pins and wires to the BeagleBone Black. Installed Ubuntu 18.14, NodeJS, npm socket.io and Bonescript(Script dedicated to BeagleBone).
I am not using Cloud 9 IDE to run the server.js and index.html.
But I use terminal in Ubuntu.
To start the server i use this command: node server.js
I tried for several days to make the server and index.html to run,
but I get this error or nothing happends:
/home/ubuntu/bonescript/server.js:42
var io = require('socket.io').listen(server);
^
[TypeError: require(...).listen is not a function
at Object.<anonymous> (/home/ubuntu/bonescript/server.js:42:31)
at Module._compile (internal/modules/cjs/loader.js:1137:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1157:10)
at Module.load (internal/modules/cjs/loader.js:985:32)
at Function.Module._load (internal/modules/cjs/loader.js:878:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)
at internal/main/run_main_module.js:17:47
Can anyone help me pinpoint the problem? I am really stuck on this stage. Thanks.
index.html code:
<!DOCTYPE html>
<html>
<head>
<title>Home Automation Web Server with BeagleBone</title>
<script src = "/socket.io/socket.io.js" ></script>
<script>
// Establishing connection with server
var socket = io.connect();
// Changes the led state
function changeState(state){
if (state==1){
// Emit message changing the state to 1
socket.emit('changeState', '{"state":1}');
// Change led status on web page to ON
document.getElementById("outputStatus").innerHTML = "Status: ON";
}
else if (state==0){
// Emit message changing the state to 0
socket.emit('changeState', '{"state":0}');
// Change led status on web page to OFF
document.getElementById("outputStatus").innerHTML = "Status: OFF";
}
}
</script>
</head>
<h2>LED</h2>
<p id="outputStatus">Status</p>
<button type="button" onclick="changeState(1);">ON</button>
<button type="button" onclick="changeState(0);">OFF</button>
</div>
</body>
</html>
server.js code:
//Loading modules
var http = require('http');
var fs = require('fs');
var path = require('path');
var b = require('bonescript');
// Create a variable called led, which refers to P9_14
var led = "P9_14";
// Initialize the led as an OUTPUT
b.pinMode(led, b.OUTPUT);
// Initialize the server on port 8888
var server = http.createServer(function (req, res) {
// requesting files
var file = '.'+((req.url=='/')?'/index.html':req.url);
var fileExtension = path.extname(file);
var contentType = 'text/html';
// Uncoment if you want to add css to your web page
/*
if(fileExtension == '.css'){
contentType = 'text/css';
}*/
fs.exists(file, function(exists){
if(exists){
fs.readFile(file, function(error, content){
if(!error){
// Page found, write content
res.writeHead(200,{'content-type':contentType});
res.end(content);
}
})
}
else{
// Page not found
res.writeHead(404);
res.end('Page not found');
}
})
}).listen(8888);
// Loading socket io module
var io = require('socket.io').listen(server);
// When communication is established
io.on('connection', function (socket) {
socket.on('changeState', handleChangeState);
});
// Change led state when a button is pressed
function handleChangeState(data) {
var newData = JSON.parse(data);
console.log("LED = " + newData.state);
// turns the LED ON or OFF
b.digitalWrite(led, newData.state);
}
// Displaying a console message for user feedback
server.listen(console.log("Server Running ..."));

I have same problem but solve it already the code on this website is based on older node version, you have to change the code on line
var io = require('socket.io').listen(server);
to
var io = require('socket.io')(server);
and edit variable or remove this line since newer node cant use .listen function twice (the code already use it on server var to open port 8888)
server.listen(console.log("Server Running ..."));

socket.io is an internal library, not an external one. Therefore, when you ran npm install socket.io, you downloaded something that is not the socket.io that you want.
Delete your node_modules, and remove socket.io from package.json, and reinstall bonescript via npm install. Then it should work.

Related

Node is not resolving a client side module

I have a Node application where I want to use socket.io to communicate data to a client where it is displayed by smoothie. I have both packages installed (via NPM) on two different node environments and in both cases in the node_modules sub-directory of my project. One of the environments is the BeagleBone Black and the other is the Cloud9 IDE environment. In both cases the socket.io module resolves and works fine but no combination of path names gets the smoothie module to resolve (which I can get to work if I just pull it from GitHub directly).
Here are the relevant bits of the server side code for the Cloud9 IDE:
var app = require('http').createServer(handler)
, io = require('socket.io').listen(app)
, fs = require('fs')
app.listen(process.env.PORT, process.env.IP);
function handler (req, res) {
fs.readFile(__dirname + '/NotWorking.html',
function (err, data) {
if (err) {
res.writeHead(500);
return res.end('Error loading index.html');
}
res.writeHead(200);
res.end(data);
});
}
.
.
.
Here are the relevant bits from the client side:
<!DOCTYPE html>
<html>
<head>
<script src="smoothie/smoothie.js"></script>
<script src="socket.io/socket.io.js"></script>
<script>
var line1 = new TimeSeries();
var line2 = new TimeSeries();
var socket = io.connect('http://demo-project.wisar.c9.io/');
socket.on('news', function (data) {
for (var property in data) {
dataPoint = data[property];
}
line1.append(new Date().getTime(), dataPoint);
line2.append(new Date().getTime(), 40);
socket.emit('my other event', { my: dataPoint });
});
</script>
.
.
.
As I said, both modules are located in the node_modules sub directory of the project directory where the above scripts live. The node documentation describes how includes are supposed to be resolved (http://nodejs.org/api/modules.html#modules_all_together) and I think that I can follow the path to how it resolves the link to socket.io by way of the index.js route...but it also works when I put a "/" in front which I can not find a path for. No permutation or combination of paths makes the smoothie module resolve. smoothie, btw, is a small charting application that can be found in npm under that name.
Any help would be appreciated.
If your current file is in the same directory as node_modules, then to load smoothie try this path in src of script tag:
./node_modules/smoothie/smoothie.js
The path smoothie/smoothie.js is not giving the location of smoothie.js, which lies in node_modules/smoothie/smoothie.js. This worked for me, I hope this works for you.

SVG to PNG Server side - using node.js

I'm trying to follow this tutorial on converting a d3.js SVG Vis to a PNG server-side (using Node.js) http://eng.wealthfront.com/2011/12/converting-dynamic-svg-to-png-with.html
Link to full code: https://gist.github.com/1509145
However, I keep getting this error whenever I attempt to make a request to load my page
/Users/me/Node/node_modules/jsdom/lib/jsdom.js:171
features = JSON.parse(JSON.stringify(window.document.implementation._fea
^
TypeError: Cannot read property 'implementation' of undefined
at exports.env.exports.jsdom.env.processHTML (/Users/dereklo/Node/node_modules/jsdom/lib/jsdom.js:171:59)
at Object.exports.env.exports.jsdom.env (/Users/dereklo/Node/node_modules/jsdom/lib/jsdom.js:262:5)
at Server.<anonymous> (/Users/dereklo/Node/Pie/pie_serv.js:26:9)
at Server.EventEmitter.emit (events.js:91:17)
at HTTPParser.parser.onIncoming (http.js:1785:12)
at HTTPParser.parserOnHeadersComplete [as onHeadersComplete] (http.js:111:23)
at Socket.socket.ondata (http.
Does anybody know why this might be? I've installed the jsdom module fine, so I don't really know what's causing these issues...thanks in advance.
EDIT
This is the code I'm using to implement the node.js server. My latest issue is below this source...
var http = require('http'),
url = require('url'),
jsdom = require('jsdom'),
child_proc = require('child_process'),
w = 400,
h = 400,
__dirname = "Users/dereklo/Node/pie/"
scripts = ["/Users/dereklo/Node/pie/d3.min.js",
"/Users/dereklo/Node/pie/d3.layout.min.js",
"/Users/dereklo/Node/pie/pie.js"],
//scripts = ["./d3.v2.js",
// "./d3.layout.min.js",
// "./pie.js"]
htmlStub = '<!DOCTYPE html><div id="pie" style="width:'+w+'px;height:'+h+'px;"></div>';
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'image/png'});
var convert = child_proc.spawn("convert", ["svg:", "png:-"]),
values = (url.parse(req.url, true).query['values'] || ".5,.5")
.split(",")
.map(function(v){return parseFloat(v)});
convert.stdout.on('data', function (data) {
res.write(data);
});
convert.on('exit', function(code) {
res.end();
});
jsdom.env({features:{QuerySelector:true}, html:htmlStub, scripts:scripts, done:function(errors, window) {
var svgsrc = window.insertPie("#pie", w, h, values).innerHTML;
console.log("svgsrc",svgsrc);
//jsdom's domToHTML will lowercase element names
svgsrc = svgsrc.replace(/radialgradient/g,'radialGradient');
convert.stdin.write(svgsrc);
convert.stdin.end();
}});
}).listen(8888, "127.0.0.1");
console.log('Pie SVG server running at http://127.0.0.1:8888/');
console.log('ex. http://127.0.0.1:8888/?values=.4,.3,.2,.1');
Latest Issue
events.js:66
throw arguments[1]; // Unhandled 'error' event
^
Error: This socket is closed.
at Socket._write (net.js:519:19)
at Socket.write (net.js:511:15)
at http.createServer.jsdom.env.done (/Users/dereklo/Node/Pie/pie_serv.js:38:19)
at exports.env.exports.jsdom.env.scriptComplete (/Users/dereklo/Node/node_modules/jsdom/lib/jsdom.js:199:39)
This may prove to be a useful answer to your question if you take out that "using node.js" stipulation. If it doesn't help you, maybe later visitors will find it interesting.
I've been working for some time to solve this same problem (server-side d3 rasterizing), and I've found PhantomJS to be the best solution.
server.js:
var page = require('webpage').create(),
renderElement = require('./renderElement.js'),
Routes = require('./Routes.js'),
app = new Routes();
page.viewportSize = {width: 1000, height: 1000};
page.open('./d3shell.html');
app.post('/', function(req, res) {
page.evaluate(new Function(req.post.d3));
var pic = renderElement(page, '#Viewport');
res.send(pic);
});
app.listen(8000);
console.log('Listening on port 8000.');
Routes.js: https://gist.github.com/3061477
renderElement.js: https://gist.github.com/3176500
d3shell.html should look something like:
<!DOCTYPE HTML>
<html>
<head>
<title>Shell</title>
</head>
<body>
<div id="Viewport" style="display: inline-block"></div>
<script src="http://cdnjs.cloudflare.com/ajax/libs/d3/2.8.1/d3.v2.min.js" type="text/javascript"></script>
</body>
</html>
You can then start the server with phantomjs server.js and POST d3=[d3 code that renders to #Viewport], and the server will respond with a base64-encoded png.
(Requires PhantomJS 1.7 or higher.)

now.js : "Object has no method" error message when trying to start server.js

I installed node.js and now.js successfully.
For now.js, this is how I did:
npm install now -g
npm install now (had to add this one. Without it, I get a "Cannot find now..." error message)
When I start the node server and provide a server.js file like this:
var httpServer = require('http');
httpServer.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write('Node is ok');
res.end();
}).listen(8080);
console.log('Server runs on http://xxxxx:8080/');
Everything is fine.
Now, I'm trying to add to this file a basic use of now.js:
var nowjs = require("now");
var everyone = nowjs.initialize(httpServer);
everyone.now.logStuff = function(msg){
console.log(msg);
}
I create an index.html file in the same folder (for testing purposes)
<script type="text/javascript" src="nowjs/now.js"></script>
<script type="text/javascript">
now.ready(function(){
now.logStuff("Now is ok");
});
</script>
This time, this is what I get on the terminal when starting the server:
Server runs on http://xxxxx:8080/
[TypeError: Object #<Object> has no method 'listeners']
TypeError: Object #<Object> has no method 'listeners'
at Object.wrapServer (/home/xxxx/node_modules/now/lib/fileServer.js:23:29)
at [object Object].initialize (/home/xxxx/node_modules/now/lib/now.js:181:14)
at Object.<anonymous> (/home/xxxx/server.js:10:22)
at Module._compile (module.js:444:26)
at Object..js (module.js:462:10)
at Module.load (module.js:351:32)
at Function._load (module.js:309:12)
at module.js:482:10
at EventEmitter._tickCallback (node.js:245:11)
Please keep in mind that I'm an absolute beginner.
Thank you for your help
'npm install -g' installs modules at a global level, often with the intent of providing system-wide binaries for terminal usage. Think Ruby Gems. If you want to include a module as part of your project you need to remove the -g.
Also, your httpServer variable is not your server but rather the http module. createServer() returns a server object which you want to capture with a variable to use in your nowjs.initialize() method as follows:
var http = require('http')
, now = require('now')
// Returns an Http Server which can now be referenced as 'app' from now on
var app = http.createServer(
//... blah blah blah
)
// listen() doesn't return a server object so don't pass this method call
// as the parameter to the initialize method below
app.listen(8080, function () {
console.log('Server listening on port %d', app.address().port)
})
// Initialize NowJS with the Http Server object as intended
var everyone = nowjs.initialize(app)

How to Use CasperJS in node.js?

I would like to use CasperJS in node.js.
I have referred to the following URL's to use CasperJS in node.js:
https://github.com/sgentle/phantomjs-node
http://casperjs.org/index.html#faq-executable
With the help of the above URLs I have written the following code:
//DISPLAY=:0 node test2.js
var phantom = require('phantom');
console.log('Hello, world!');
phantom.create(function (ph) {
ph.casperPath = '/opt/libs/casperjs'
ph.injectJs('/opt/libs/casperjs/bin/bootstrap.js');
var casper = require('casper').create();
casper.start('http://google.fr/');
casper.thenEvaluate(function (term) {
document.querySelector('input[name="q"]').setAttribute('value', term);
document.querySelector('form[name="f"]').submit();
}, {
term: 'CasperJS'
});
casper.then(function () {
// Click on 1st result link
this.click('h3.r a');
});
casper.then(function () {
console.log('clicked ok, new location is ' + this.getCurrentUrl());
});
casper.run();
});
When I run this code, I got the following error:
ERROR MSG:
tz#tz-ubuntu:/opt/workspaces/TestPhantomjs$ DISPLAY=:0 node test2.js
Hello, world!
Error: Cannot find module 'casper'
at Function._resolveFilename (module.js:332:11)
at Function._load (module.js:279:25)
at Module.require (module.js:354:17)
at require (module.js:370:17)
at /opt/workspaces/TestPhantomjs/test2.js:6:14
at Object.<anonymous> (/opt/workspaces/TestPhantomjs/node_modules/phantom/phantom.js:82:43)
at EventEmitter.<anonymous> (/opt/workspaces/TestPhantomjs/node_modules/phantom/node_modules/dnode/index.js:215:30)
at EventEmitter.emit (events.js:67:17)
at handleMethods (/opt/workspaces/TestPhantomjs/node_modules/phantom/node_modules/dnode-protocol/index.js:138:14)
at EventEmitter.handle (/opt/workspaces/TestPhantomjs/node_modules/phantom/node_modules/dnode-protocol/index.js:98:13)
phantom stdout: Unable to load casper environment: Error: Failed to resolve module fs, tried fs
You can use SpookyJS to drive CasperJS from Node.
https://groups.google.com/group/casperjs/browse_thread/thread/641e9e6dff50fb0a/e67aaef5ab4ec918?hl=zh-CN#e67aaef5ab4ec918
Nicolas Perriault
2012/2/27 天猪 蓝虫. :
I wan to use casperjs in nodejs.
and refs to:
https://github.com/sgentle/phantomjs-node and
http://casperjs.org/index.html#faq-executable
You can't run CasperJS that way; QtWebKit and V8 don't share the same
js environment (and event loop), so your node.js app won't be able to
load and use a CasperJS module. You have to run your CasperJS script
separately using a subprocess call, like this one on github. I
don't plan to make CasperJS compatible with phantomjs-node because it
uses alert()-based dirty hacks I'm not easy with.
Cheers,
-- Nicolas Perriault
CasperJS includes a web server to talk to the outside world. Node (using request, superagent etc) can now talk to casper over HTTP.
In scraper.js:
#!/usr/bin/env casperjs
// I AM NOT NODEJS
// I AM CASPER JS
// I RUN IN QTWEBKIT, NOT V8
var casper = require('casper').create();
var server = require('webserver').create();
var ipAndPort = '127.0.0.1:8585';
server.listen(ipAndPort, function(request, response) {
casper.start('https://connect.data.com/login');
casper.userAgent("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36");
casper.then(function(){
// lots of code here, and a few more cassper.then()s
});
casper.run(function(){
console.log('\n\nFinished')
response.statusCode = 200;
var body = JSON.stringify({
phoneNumber: '1800-YOLO-SWAG'
})
response.write(body);
response.close();
});
});
You can now run scraper.js as a web server:
chmod +x scraper.js
./scraper.js
You should run it as a Linux service just like you would for a node app.
One solution (which worked for me) is to start and stop your server on a per-test basis. For example, I have a runtests.coffee which looks like:
http = require 'http'
glob = require 'glob'
spawn = require('child_process').spawn
db = require './db' # Contains all database stuff.
webapp = require './webapp' # Contains all of the Express stuff.
db.connect 'test' # Connects to the db server and creates an empty test db.
server = http.createServer webapp.makeApp()
server.listen 0, ->
port = server.address().port
process.env.URL = "http://localhost:#{ port }"
glob 'tests/*', (err, filenames) ->
child = spawn 'casperjs', ['test'].concat(filenames)
child.stdout.on 'data', (msg) -> process.stdout.write msg
child.stderr.on 'data', (msg) -> process.stderr.write msg
child.on 'exit', (code) ->
db.disconnect() # Drops the test db.
server.close()
process.exit code
And my CasperJS tests in tests/ look like:
URL = require('system').env.URL # Note, Casper code here, not Node.
casper.test.begin 'Test something', 1, (test) ->
casper.start "#{ URL }/welcome"
casper.then ->
test.assertHttpStatus 200
# ....
casper.run ->
test.done()
It basically means that your script can't find Casper; have you checked the path and made sure that
/opt/libs/casperjs
and:
/opt/libs/casperjs/bin/bootstrap.js
Are accessible by a website user ? considering the location it's probably not likely.
/opt is a unix path, but the website will be looking in {websiterootpath}/opt.
I'd create a subfolder 'casperjs' in the root folder of your website and copy the contents of
/opt/libs/casperjs
To there.
Then change your paths from
/opt/libs/casperjs
To
/casperjs
I tried to run casper by node cron job too,
here's my solution
in casper.js echo your response:
casper.then(function() {
var comments = this.evaluate(getComments);
this.echo(JSON.stringify(comments));
})
use node-cmd in node file casper_wrapper.js:
var cmd = require('node-cmd');
module.exports = function(url) {
return new Promise(function(resolve, reject) {
cmd.get(
'casperjs casper.js ' + url, // casper takes args to run the script
function(err, data, stderr){
if (err) {
reject(err);
return;
}
var obj = JSON.parse(data);
resolve(obj);
}
);
});
}

Making an HTTP request using node.js throws EAFNOSUPPORT

I'm trying to make a simple HTTP GET request using node.js, but I'm running into trouble using node.js v0.3.4-pre (i.e. compiled from HEAD as of this morning). Here's my code:
var cli = require('cli');
var http = require('http');
var url = require('url');
cli.parse();
cli.main(function(args, opts) {
this.debug(args[0]);
var siteUrl = url.parse(args[0]);
var site = http.createClient(siteUrl.port, siteUrl.host);
console.log(siteUrl);
var request = site.request("GET", siteUrl.pathname, {'host' : siteUrl.host})
request.end();
request.on('response', function(response) {
response.setEncoding('utf8');
console.log('STATUS: ' + response.statusCode);
response.on('data', function(chunk) {
console.log("DATA: " + chunk);
});
});
});
Here's the error that I get:
node.js:68
throw e; // process.nextTick error, or 'error' event on first tick
^
Error: EAFNOSUPPORT, Address family not supported by protocol family
at doConnect (net.js:499:19)
at Client.connect (net.js:652:30)
at Client._ensureConnection (http.js:1033:10)
at Client.request (http.js:1048:8)
at Object.<anonymous> (/Users/paul/Desktop/readify.js:16:21)
at /usr/local/lib/node/.npm/cli/0.2.3-2/package/cli.js:995:18
at Object.main (/usr/local/lib/node/.npm/cli/0.2.3-2/package/cli.js:1000:9)
at Object.<anonymous> (/Users/paul/Desktop/readify.js:10:5)
at Module._compile (node.js:359:32)
at Object..js (node.js:367:14)
Found the bug, siteUrl.port will be undefined unless the URL explicitly names a port. So, the solution is:
var site = http.createClient(siteUrl.port || 80, siteUrl.host);
var site = http.createClient(siteUrl.port, siteUrl.host);
should rather be
var site = http.createClient(siteUrl.port || 80, siteUrl.hostname);
The same error message appeared on my very old XPSP2-box for ANY connect()-attempts. E.g npm wasn't able to do anything, and simple http requests failed.
While trying to find a solution, this post appeared all over the place, but its not the same issue.
In my case it had to do with WSAIoctl(...) always returning WSAEOPNOTSUPP when querying for WSAID_CONNECTEX, which seemed strange. This led me to a post recommending doing a "netsh winsock reset" from the cmd, which fixed the problem!

Resources