I'm trying this code:
var connect = require("connect");
var io = require("socket.io");
var spawn = require("child_process").spawn;
var server = connect.createServer(
connect.favicon(),
connect.logger(),
connect.staticProvider(__dirname + '/public')
);
server.listen(8000);
var socket = io.listen(server, {flashPolicyServer: false});
var tail = spawn("tail", ["-f", "./nohup.out"]);
tail.stdout.on("data", function(data) {
socket.broadcast(data.toString("utf8"));
});
But when I try to run this I got an error:
Nathan-Camposs-MacBook-Pro:log Nathan$ node app.js
node.js:134
throw e; // process.nextTick error, or 'error' event on first tick
^
TypeError: Object function createServer() {
if ('object' == typeof arguments[0]) {
return new HTTPSServer(arguments[0], Array.prototype.slice.call(arguments, 1));
} else {
return new HTTPServer(Array.prototype.slice.call(arguments));
}
} has no method 'staticProvider'
at Object.<anonymous> (/Users/Nathan/Sites/log/app.js:8:10)
at Module._compile (module.js:407:26)
at Object..js (module.js:413:10)
at Module.load (module.js:339:31)
at Function._load (module.js:298:12)
at Array.<anonymous> (module.js:426:10)
at EventEmitter._tickCallback (node.js:126:26)
Nathan-Camposs-MacBook-Pro:log Nathan$
I don't really know the connect library. But this documentation says, that it's static not staticProvider (in the version 1.0).
So your server creating part should be:
var server = connect.createServer(
connect.favicon(),
connect.logger(),
connect.static(__dirname + '/public')
);
Related
I am trying to run parse server with nodejs in ibm bluemix but it is throwing an error in parse server PromiseRouter file.
PromiseRouter.js:48
throw _iteratorError;
^
ReferenceError: Symbol is not defined
How can i get this resolved
My App .js
var express = require('express');
var ParseServer = require('parse-server').ParseServer;
var app = express();
var port = process.env.PORT || 1337;
// Specify the connection string for your mongodb database
// and the location to your Parse cloud code
var api = new ParseServer({
databaseURI: 'mongodb://IBM_MONGO_DB',
cloud: './cloud/main.js', // Provide an absolute path
appId: 'MYAPPID',
masterKey: 'MYMASTER_KEY', //Add your master key here. Keep it secret!
serverURL: 'http://localhost:' + port + '/parse' // Don't forget to change to https if needed
});
app.use('/parse', api);
app.get('/', function(req, res) {
res.status(200).send('Express is running here.');
});
app.listen(port, function() {
console.log('parse-server-example running on port ' + port + '.');
});
Response :
/Applications/MAMP/htdocs/IBM_bluemix/Development/my_node_app/node_modules/parse-server/lib/PromiseRouter.js:48
throw _iteratorError;
^
ReferenceError: Symbol is not defined
at PromiseRouter.merge (/Applications/MAMP/htdocs/IBM_bluemix/Development/my_node_app/node_modules/parse-server/lib/PromiseRouter.js:33:40)
at new ParseServer (/Applications/MAMP/htdocs/IBM_bluemix/Development/my_node_app/node_modules/parse-server/lib/index.js:137:10)
at Object.<anonymous> (/Applications/MAMP/htdocs/IBM_bluemix/Development/my_node_app/app.js:10:11)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:906:3
This is the function in PromiseRouter.js that is throwing an error
PromiseRouter.prototype.merge = function (router) {
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = router.routes[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var route = _step.value;
this.routes.push(route);
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
};
This is all i have
The reason why Symbol is not found is because it is an ES6 feature that is not supported in your current Node.js build. Check to make sure your Node.js runtime is at least v4 (see compatibility here).
The easy way to ensure your Node.js build on Bluemix is running at least v4.0 is to define your engine variable in your app's package.json file as such:
{ "engines" : { "node" : ">=4.0" } }
After updating your package.json file, re-push your application to Bluemix and it will build it with your defined version of Node.js
I have a following NodeJS server file that is supposed to handle following JSON Message:
If received message as key, send some response.
If received app as key, send some DLL to the client.
Now I am interested in handling multiple clients that will, for this case, send only message as Key in JSON.
Here is the code:
var net = require('net');
var fs = require('fs');
var util = require('util');
var server = net.createServer(function(c) { //'connection' listener
console.log('client connected');
c.on('end', function() {
console.log('client disconnected');
});
c.on('data', function(data) {
var json = JSON.parse(data.toString());
if(json.heartbeat){
if(json.first_fetch === "1"){
c.write("{\"config_changed\":\"true\",\"config\":\"This is some config\"}"); // JSON Message here
}
else{
c.write("{\"config_changed\":\"false\"}");
}
}
else if(json.message){
c.write("{\"success\":\"true\"}");
}
else if(json.app){
fs.exists('apps/'+ json.app + ".dll", function (exists) {
util.debug(exists ? "it's there" : "Its not there");
});
var stats = fs.statSync('apps/'+ json.app + ".dll")
var fileSizeInBytes = stats["size"]
var message = json.app + "\n" + fileSizeInBytes + "\n";
c.write(message);
fs.open('apps/'+ json.app + ".dll","r", function(status, fd){
console.log(fd);
var read_bytes = 0;
var fileStream = fs.createReadStream('apps/'+ json.app + ".dll");
fileStream.on('data',function(chunk){
c.write(chunk);
});
})
}
else
{
c.write("{\"some\":\"error\"}");
}
});
c.on('error', function (e) {
console.log(e);
});
// c.pipe(c);
});
server.listen(1936, function() { //'listening' listener
console.log('server bound');
});
My client will send message as {"message":"This is message"}, and server will send {"success":"true"}. I received following benchmark of the server I created:
One client sent 200000 message in 7 seconds.
Two clients, each sent message in 13/14 seconds.
Three clients, each sent message in 17/17/16 seconds.
The time for each client reduces significantly when they are sending message to one server. I tried to run multiple server at once, but it gave:
events.js:85
throw er; // Unhandled 'error' event
^
Error: listen EADDRINUSE
at exports._errnoException (util.js:746:11)
at Server._listen2 (net.js:1156:14)
at listen (net.js:1182:10)
at Server.listen (net.js:1267:5)
at Object.<anonymous> (C:\Users\Dell\Desktop\nodeserver\server.js:54:8)
at Module._compile (module.js:460:26)
at Object.Module._extensions..js (module.js:478:10)
at Module.load (module.js:355:32)
at Function.Module._load (module.js:310:12)
at Function.Module.runMain (module.js:501:10)
If I want to get the performance of 200K in 7 seconds for each of clients, how am I to proceed. I want to run multiple instance of servers, with a load balancer to improve the server efficiency. I am using Windows.
try to use node.js Cluster module for this
https://nodejs.org/api/cluster.html
different nodejs instances can't share same port
another approach is to use external load balancer, nginx for example
http://nginx.org/en/docs/http/load_balancing.html
I am learning Node.js. I just found about module.exports. It seems to me that this is a way to help keep code clean and maintainable by separating code.
I tried out a few examples and it works. I got to console.log a few things by calling the method and it ran the function that was on another file.
I also learned some socket.io. I have got it to work as well.
I wanted to separate the code so I put all the socket.io connection information in a separate file and called the method on the main server file.
It doesn't work. The only way everything works if all the code is on the same page.
This is what I have:
app.js
var app = require('express')();
var ioConnect = require('./ioConnect.js')
var server = require('http').Server(app);
var io = require('socket.io')(server);
server.listen(80);
ioConnect.ioConnection();
ioConnect.js
function addScore() {
var io = require('socket.io');
io.on('connection', function(socket) {
socket.on('score', function(data) {
socket.emit('addScore', 15);
});
});
}
module.exports.ioConnection = addScore;
At first I got an error that said: "io is not defined" so I added
var io = require('socket.io)(server); and got server is not defined so I tried
var io = require('socket.io'); and got this error:
/root/game/ioConnect2.js:5
io.on('connection', function(socket) {
^
TypeError: Object function Server(srv, opts){
if (!(this instanceof Server)) return new Server(srv, opts);
if ('object' == typeof srv && !srv.listen) {
opts = srv;
srv = null;
}
opts = opts || {};
this.nsps = {};
this.path(opts.path || '/socket.io');
this.serveClient(false !== opts.serveClient);
this.adapter(opts.adapter || Adapter);
this.origins(opts.origins || '*:*');
this.sockets = this.of('/');
if (srv) this.attach(srv, opts);
} has no method 'on'
at Object.addScore [as ioConnection] (/root/game/ioConnect2.js:5:16)
at Object.<anonymous> (/root/game/app:8:19)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:906:3
If I put the code together on one file everything works. Can someone please explain to me exactly whats going on here and what I need to do?
When you require socket.io it returns a function. In app.js you called that require/function with an argument and stored the return value in 'io'. Good so far. In ioConnect.js you are storing the function itself in io. rather than do that, you should pass the io you set in app.js to the function returned by your require of ioConnect.js.
app.js
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
var ioConnect = require('./ioConnect.js')(io);
server.listen(80);
ioConnect.addScore();
ioConnect.js
function ioConnection(io) {
if (!(this instanceof ioConnection)) {
return new ioConnection(io);
}
this.io = io;
}
ioConnection.prototype.addScore = function() {
this.io.on('connection', function (socket) {
socket.on('score', function (data) {
socket.emit('addScore', 15);
});
});
}
module.exports = ioConnection;
As the title says, I have a problem with what node.js command prompt says lies in the requestHandlers.js file. I am following the guide in the Node Beginner Book and until now, there have not been any problems with the book - or rather my code.
I have the following input:
index.js:
var server = require("./server");
var router = require("./router");
var requestHandlers = require("./requestHandlers");
var handle = {}
handle["/"] = requestHandlers.start;
handle["/start"] = requestHandlers.start;
handle["/upload"] = requestHandlers.upload;
server.start(router.route, handle);
server.js:
var http = require("http");
var url = require("url");
function start(route, handle) {
function onRequest(request, response) {
var pathname = url.parse(request.url).pathname;
console.log("Request for " + pathname + " received.");
route(handle, pathname);
response.writeHead(200, {"Content-Type": "text/plain"});
response.write("Hello World");
response.end();
}
http.createServer(onRequest).listen(8888);
console.log("Server has started.");
}
exports.start = start;
router.js
function route(handle, pathname) {
console.log("About to route a request for " + pathname);
if (typeof handle[pathname] === 'function') {
handle[pathname]();
} else {
console.log("No request handler found for " + pathname);
}
}
exports.route = route;
requestHandlers.js
function start() {
console.log("Request handler "start" was called.");
}
function upload() {
console.log("Request handler "upload" was called.");
}
exports.start = start;
exports.upload = upload;
And I have this output:
"C:\Program Files (x86)\nodejs\requestHandlers.js:1
console.log("Request handler "start" was
SyntaxError: Unexpected identifier
at Module._compile (module.js:439:25)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Module.require (module.js:364:17)
at require (module.js:380:17)
at Object.<anonymous> (C:\Program Files (x86)\nodejs\index.js:1:153)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)"
I can't really see where the problem lies. I have followed the guide in the book and I have either copy-pasted the code from the book or written it myself. I have doublechecked the code for errors, but have not found any. I have remembered to use \'function\' for instance, so there would not be any mistakes in the code when entering it in node.js.
So any help would be appreciated!
Thanks.
You're mixing the different string markers in JavaScript.
function start() {
console.log("Request handler "start" was called.");
}
function upload() {
console.log("Request handler "upload" was called.");
}
You can use " for the start and end of a string, but something like "Request handler "start" was called."
Is invalid, because you terminate the string at "start and start a new string at "was called.
If start and upload are variables just concatenate the strings with something like this:
"Request handler " + start + " was called."
or change your string to something like this:
"Request handler 'start' was called."
or remove the " around start and upload.
I've check such kind of issue. but i don't find any. if you found it. just let me know.
I just getting started write javascript through node.js, and serialport. cand someone explain me why this error appear?
/Applications/MAMP/htdocs/homeautomation/server.js:42
var sp = new serialPort(portName, {
^
TypeError: undefined is not a function
at Object.<anonymous> (/Applications/MAMP/htdocs/homeautomation/server.js:42:10)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:901:3
this is my starting code
/*
* dependencies
*/
var express = require('express'),
server = require('http').createServer(app),
io = require('socket.io').listen(server),
serialPort = require('serialport').serialPort;
server.listen(3000);
console.log('listen on port 3000')
/*
* Express
*/
var app = express();
// serve static files from index
app.configure(function(){
app.use(express.static(__dirname + '/'));
});
// respon to web GET request on index.html
app.get('/', function (req, res){
res.sendfile(__dirname + '/index.html');
});
/*
* Serial Port Setup
*/
var portName = '/dev/tty.usb.serial-A501JUTF';
//var portName = '/dev/tty.usbmodem1421';
var readData = ''; //Array to hold the values read from the port
var sp = new serialPort(portName, {
baudRate : 9600,
dataBits : 8,
parity : 'none',
stopBits: 1,
flowControl : false,
});
any help will be appreciated.
Your code is correct, except that you used the serialPort object of the require('serialport') library, when it's in fact SerialPort that you need to use, hence the undefined is not a function error that you encountered.
var SerialPort = require("serialport")
console.log(SerialPort.serialPort); // undefined
console.log(SerialPort.SerialPort); // { [Function: SerialPort, ... }
See the documentation for a sample usage.
Try this. It works perfectly.
var SerialPort = require('serialport');
var serialPort = SerialPort.serialPort;
var sp = new SerialPort("/dev/ttyACM0", {
});