var app = require('http').createServer(handler);
var Rcon = require('rcon');
var url = require('url');
app.listen(7777);
console.log('Server started.');
function handler (req, res) {
console.log('New connection!');
res.writeHead(200);
var urlParts = url.parse(req.url, true);
var server = urlParts.query;
var conn = new Rcon(server.ip, server.port, server.password);
conn.on('auth', function() {
conn.send(server.command);
console.log('Sent command!');
}).on('response', function(data) {
res.end(data);
console.log('Response: '+data);
}).on('error', function(data) {
res.end('error');
console.log('Error: '+data);
}).on('err', function(data) {
res.end('error');
console.log('Error: '+data);
});
conn.connect();
}
All of that works perfectly on localhost but when I upload to a remote server and run it, it responds with error in browser and with this in the console:
Server started. New connection! Error: TypeError: Object 0�P�q has no
method 'writeInt32LE' New connection! Error: Error: EINVAL, Invalid
argument
First guess: rcon module contains compiled extensions and you checked the files of node_modules/rcon into git and then tried to run them on a different CPU architecture. You need to run npm rebuild on the remote server for a quick fix and to get your node_modules folder out of your git repository as the correct long-term fix.
Related
I tried to build a chat box server by node.js. When the browser requestes the page, it workes well at first. But when I refresh the page, the Server crashes.
Below is the error message:
events.js:183
throw er; // Unhandled 'error' event
^
Error: read ECONNRESET
at _errnoException (util.js:1022:11)
at TCP.onread (net.js:615:25)
I used the node --inspect index.js, but could not find the point.
Below is the code of index.js:
const http = require('http');
const fs = require('fs');
const extract = require('./extract');
const wss = require('./websockets-server');
var handleError = function (err,res) {
res.writeHead(404);
res.end();
}
var server = http.createServer(function (req, res) {
console.log("Responding to a request.");
var filePath = extract(req.url);
console.log("filePath:"+filePath);
fs.readFile(filePath,function (err,data) {
if(err){
handleError(err,res);
return;
}else {
res.end(data);
}
})
})
server.listen(3000);
When I comment the 4th line, the import of websockets-server. Server works well when I refresh the page. Maybe it's about the websocket while it works without websocket.
Below is code of websockets-server.js:
const WebSocket = require('ws');
var WebSocketServer = WebSocket.Server;
var port = 3001;
var ws = new WebSocketServer({
port:port
});
var message = [];
console.log('websockets server started');
ws.on('connection', function (socket) {
console.log('client connection established');
message.forEach(function (msg) {
socket.send(msg);
})
socket.on('message', function (data) {
console.log('message received: ' + data);
message.push(data);
ws.clients.forEach(function (clientSocket) {
clientSocket.send(data);
});
});
});
Does the problem is about the websocket? Whether should I do process when the client shutdown the connection with the server while refreshing the page.
extract.js below:
const path = require('path');
var extractFilePath = function (url) {
var filePath;
var fileName = 'index.html';
if(url.length > 1){
fileName = url.substring(1);
}
console.log('The fileName is: ' + fileName);
filePath = path.resolve(__dirname, 'app', fileName);
return filePath;
}
module.exports = extractFilePath;
I guess that you maybe execute var ws = new WebSocket("ws://localhost:3001"); in html file. I haven't figured out exact reason about your error as I'm not proficient in WebSocket. But there is a solution:
window.onbeforeunload = function () {
ws.close();
}
close connection before reload, then the error will not reappear.
You need to add an error listener on the socket. Error listener only on the websocket instance does not help in this case.
socket.on('error', function(e){
console.log(e);
});
The ECONNRESET error means that the other side (browser) closed the connection abruptly. On browser refresh, browser simple killed the connection with the websocket server.
To solve this, you have to listen for the error event on the websocket server instance.
// listen for "error" event so that the whole app doesn't crash
wss.on("error", function(error){
console.log(error);
}
I was having the same problem, but it resolved after this command:
npm install #ionic/app-scripts#nightly --save-dev
I am trying to create a simple script to send data from a file every to the client every time the file is updated. I have tested and found that the file is read, but the client doesn't receive anything. there are no errors in the console. I am fairly new to socket.io.
node.js code
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var fs = require("fs");
var port = process.env.PORT || 3000;
app.get('/', function(req, res){
res.sendFile(__dirname + '/popup.html');
});
fs.watchFile("assets/popup.json", {interval:100}, function(curr, prev)
{
fs.readFile("assets/popup.json",{encoding:"utf8"}, function(err, data){
io.emit("popup", data)
})
});
http.listen(port, function(){
console.log('listening on *:' + port);
});
client code
var socket = io();
socket.on('popup', function(msg){
alert("hello")
});
Whenever things aren't working right like this, you need to resort to "debug mode". In that mode, you need to gather all possible events that might be happening and see what you learn from that. To that end, add this code to the client:
var socket = io();
socket.on('popup', function(msg){
console.log("hello: ", msg)
});
socket.on('connection', function() {
console.log("client connected");
});
socket.on('connect_error', function(err) {
console.log("client connect_error: ", err);
});
socket.on('connect_timeout', function(err) {
console.log("client connect_timeout: ", err);
});
These messages are all documented in the client-side doc on the socket.io Github site which you can find by Googling "socket.io github" at any time.
Then, see what you see in the browser console when the page loads. If you don't know how to open the browser console in whichever browser you are using, google it to find out. You need to be looking at the debug console when the page loads.
FYI, we're assuming that you've loaded socket.io into the page via a script tag before this code. If not, that error will show in the console too.
The OP then gets this error:
client connect_error:
Error: server error at Socket.onPacket (socket.io-1.2.0.js:1)
at XHR.<anonymous> (socket.io-1.2.0.js:1)
at XHR.Emitter.emit (socket.io-1.2.0.js:1)
at XHR.Transport.onPacket (socket.io-1.2.0.js:1)
at callback (socket.io-1.2.0.js:2)
at Object.exports.decodePayload (socket.io-1.2.0.js:2)
at XHR.Polling.onData (socket.io-1.2.0.js:2)
at Request.<anonymous> (socket.io-1.2.0.js:2)
at Request.Emitter.emit (socket.io-1.2.0.js:1)
at Request.onData (socket.io-1.2.0.js:2)
OK, progress. How are you loading socket.io in the client page? This seems like it might be that you have mismatched versions of socket.io in client and server. You should be doing:
<script src="/socket.io/socket.io.js"></script>
and then your server will be feeding the client page the exact same version of socket.io. Also, since this error reports client-side socket.io 1.2.0, what version of socket.io is installed on the server?
try this
socket.on('popup', function(msg){
socket.emit('message',"popup");
});
The issue appears to be you don't actually connect to a local socket.io server. By running node server.js with the code below you can start a web server. Then navigate to localhost in your browser to see the changes in console made to popup.json.
server.js
var app = require('http').createServer(handler);
var io = require('socket.io')(app);
var fs = require('fs');
app.listen(80);
function handler (req, res) {
fs.readFile(__dirname + '/index.html',
function (err, data) {
if (err) {
res.writeHead(500);
return res.end('Error loading index.html');
}
res.writeHead(200);
res.end(data);
});
}
fs.watchFile("popup.json", {interval: 100}, function (curr, prev) {
fs.readFile("popup.json", {encoding: "utf8"}, function (err, data) {
io.emit("popup", JSON.parse(data));
})
});
index.html
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io('http://localhost');
socket.on('popup', function (data) {
console.log(data);
});
</script>
I have a weird bug going on with my code.
I'm using the simple-oauth2 library (https://github.com/lelylan/simple-oauth2) and my code works fine on Windows.
When I try to run my code on a linux server (raspberry pi zero), the oauth library keeps on returning 404 Not Found for my oauth request (specifically "Access Token Error Not Found" as per the code below).
What's going on?
Code (working with Yelp API):
var fs = require('fs');
var cID = fs.readFileSync('blahblahblah', 'utf8');
var cSecret = fs.readFileSync('blahblahblah2', 'utf8');
var credentials = {
client: {
id: cID,
secret: cSecret
},
auth: {
tokenHost: 'https://api.yelp.com',
tokenPath: '/oauth2/token'
}
};
var oauth2 = require('simple-oauth2').create(credentials);
var tokenConfig = {};
module.exports.gimmeMuhToken = function(cb) {
oauth2.clientCredentials.getToken(tokenConfig, function(error, result) {
if (error) {
return console.log('Access Token Error', error.message);
}
cb(oauth2.accessToken.create(result).token.access_token); // Return the token
});
};
Thanks
Found the culprit.
It was line endings...
I am trying to retrieve data from a REST API in the server side (.js) and display it in my view (.jade)
I was able to get the data but was not able to send it to the view .
This is how my code looks like :
var BugData ='initial data' ;
var https = require('https');
var optionsget = {
rejectUnauthorized: false,
host : 'My host', // here only the domain name
// (no http/https !)
port : 443,
path : 'Mypath', // the rest of the url with parameters if needed
method : 'GET' // do GET
};
console.info('Options prepared:');
console.info(optionsget);
console.info('Do the GET call');
// do the GET request
var reqGet = https.request(optionsget, function(res) {
console.log("statusCode: ", res.statusCode);
res.on('data', function(d) {
console.info('GET result:\n');
BugData =d;
console.log('Show Data : ***** \n' +d);
});
});
reqGet.end();
reqGet.on('error', function(e) {
console.error(e);
});
res.render('index', { ab:BugData});
BugData (was defined before )is the variable i am trying to send to the view but for some reasons it is empty and does not contain the variable 'd'
Does anyone know why or how can i solve this ?
Thanks
There is no need to write that long code.
Be simple, follow these steps:
1) install request package:
npm install --save request
2) outside of router add:
var request = require('request');
process.env.NODE_TLS_REJECT_UNAUTHORIZED = 0;
3) use this code inside router:
request.get({url: 'https://my-host/Mypath'}, function(err, response, body) {
var data = {};
if (err) {
console.error(err);
data.err = err;
}
data.ab = body;
console.log('Data: ', data);
res.render('index', data);
});
I'm planning to use nodeJS as my comet server and I wrote some code for testing, but there is an issue that when client connected to the server for the first time, it couldn't get response from server.
Here is the server-side code (server.js):
var util = require('util');
var redis = require('redis').createClient(6379, '192.168.1.254');
var http = require('http');
redis.on("error", function (err) {
console.log("Error " + err);
});
var server = http.createServer(requestListener);
server.listen(9898, '192.168.1.254');
function requestListener(req, res) {
util.log('Connected.');
redis.brpoplpush('msg:q:1', 'msg:s:1', 20, function(err, reply) {
if (err) {
util.log('ERROR: ' + err);
}
var length = reply ? reply.length : 0;
res.writeHead(200, {
'Content-Type':'text/plain',
'Content-Length':length
});
if (length) {
res.end(reply);
util.log('Sent: ' + reply);
} else {
res.end('');
}
});
}
And the client code (client.sh):
#!/bin/bash
while [ 1 ]
do
curl -i http://192.168.1.254:9898
done
I tested it following steps:
node server.js
./client.sh
In redis, LPUSH('msg:q:1', 'blablah')
Now, "Sent: blablah" printed on console, res.end(reply) excuted, but client receives nothing. I repeat step 3 for many times, then it works as expect. If I restart the client, the first few responses can't be received again.
How can I resolve this?
I think what might happening here is you've aborted curl while it was waiting for the response from redis. After the HTTP client is aborted, the redis command still stays active. You then push another element onto the queue, the redis command returns, but has no HTTP response to write it to. When you start the curl loop again, you find the queue empty.
Here's a modified version of your program that streams the response and detects a client abort. It doesn't put the element back on the queue, but you could certainly do that as well.
var util = require('util');
var redis = require('redis').createClient();
var http = require('http');
redis.on("error", function (err) {
console.log("Redis error " + err);
});
redis.on("ready", function () {
console.log("Redis client ready");
});
var server = http.createServer(requestListener);
server.listen(9898);
function requestListener(req, res) {
var aborted = false;
res.writeHead(200, {
"Content-Type": "text/plain"
});
res.write("Checking redis...\n");
redis.brpoplpush('q', 's', 20, function (err, reply) {
if (aborted) {
return console.log("Client aborted before redis reply came back.");
}
if (err) {
return res.end("Redis error");
}
res.end("Redis reply: " + reply);
});
req.on("aborted", function () {
console.log("HTTP client aborted.");
aborted = true;
});
}