I am using nodejs with mqlight to run a sample code which is provided by https://www.npmjs.com/package/mqlight.
I am using nodejs 5.5.0 and npm version is 3.3.12.
I installed mqlight using npm install mqlight.
var mqlight = require('mqlight');
var recvClient = mqlight.createClient({service: 'amqp://localhost'});
var topicPattern = 'public';
recvClient.on('started', function() {
recvClient.subscribe(topicPattern);
recvClient.on('message', function(data, delivery) {
console.log('Recv: %s', data);
});
});
var sendClient = mqlight.createClient({service: 'amqp://localhost'});
var topic = 'public';
sendClient.on('started', function() {
sendClient.send(topic, 'Hello World!', function (err, data) {
console.log('Sent: %s', data);
sendClient.stop();
});
});
While I am running above code I got below error.
E:\nodejs>node mqtest.js
events.js:154
throw er; // Unhandled 'error' event
^
NetworkError: CONNECTION ERROR (localhost:5672): Connect failure: The remote co
mputer refused the network connection.
at Socket.connError (E:\nodejs\node_modules\mqlight\mqlight.js:1437:19)
at emitOne (events.js:90:13)
at Socket.emit (events.js:182:7)
at emitErrorNT (net.js:1255:8)
at nextTickCallbackWith2Args (node.js:474:9)
at process._tickCallback (node.js:388:17)
Please help to solve this problem. I am using window 7 64 bit os.
Are you sure the service amqp is running? You can follow the below script to start amqp service.
START SERVICE(SYSTEM.AMQP.SERVICE)
START CHANNEL(SYSTEM.DEF.AMQP)
REFRESH SECURITY TYPE(CONNAUTH)
DISPLAY CHSTATUS(SYSTEM.DEF.AMQP) CHLTYPE(AMQP)
Related
I'm trying to print a document on the second paper tray with IPP (Internet Printing Protocol). I'm using this npm IPP-Library.
But at any time i try to print a document my printer shows a message that i need to add paper to the first paper tray and the console output of says Printed: successful-ok.
var ipp = require("ipp");
var PDFDocument = require("pdfkit");
var concat = require("concat-stream");
var doc = new PDFDocument;
doc.text("Hello World");
doc.pipe(concat(function (data) {
var printer = ipp.Printer("MY_URL");
var file = {
"operation-attributes-tag": {
"requesting-user-name": "admin",
'attributes-charset': 'utf-8',
'attributes-natural-language': 'de'
},
"printer-attributes": {
"media-col": {
"media-source": "tray-2"
},
},
data: data
};
printer.execute("Print-Job", file, function (err, res) {
console.log("Printed: " + res.statusCode);
});
}));
doc.end();
The other variant i tried is following (from here):
var PDFDocument = require("pdfkit");
let fs = require('fs')
var ipp = require('ipp');
var uri = "http://10.1.205.71";
var msg = new Buffer(
'0200'+ //Version
'000201e6d5f2'+
'01'+ //Operation attributes tag (your information in the Operation attributes might be different)
'47'+ //charset tag
'0012'+ //length
'617474726962757465732d63686172736574'+ //attributes-charset
'0005'+ //length
'7574662d38'+ //utf-8
'48'+ //natural language tag
'001b'+ //length
'617474726962757465732d6e61747572616c2d6c616e6775616765'+//attributes-natural-language
'0002'+//length
'656e'+ //en
'45'+ // URI tag
'000b'+ //length
'7072696e7465722d757269'+ //printer-uri
'0012'+//length
'687474703a2f2f31302e312e3230352e3731'+//http://10.1.205.71
'49'+ //mimeMediaType tag
'000f'+ //length
'646f63756d656e742d666f726d6174'+ //document format
'000f'+ //length
'6170706c69636174696f6e2f706466'+ //application/pdf
'02'+ //job attributes tag
'34'+ //begin collection
'0009'+ //length
'6d656469612d636f6c'+ //media-col
'0000'+ //value length
'4a'+ //collection entry
'0000'+ //name length
'000c'+ //value length
'6d656469612d736f75726365'+ //media-source
'44'+ // collection entry
'0000'+ //name length
'0006'+ //value length
'747261792d32'+ //tray-2
'37'+ //end of collection
'00000000'+ //name length and value length
'03', 'hex');
var doc = new PDFDocument;
doc.text("Hello World");
var buffers = [];
doc.on('data', buffers.push.bind(buffers));
doc.on('end', function(){
var buf = Buffer.concat(buffers);
var catBuf = Buffer.concat([msg, buf]);
ipp.request(uri, catBuf, function(err, res){
if(err){
return console.log(err);
}
console.log(JSON.stringify(res,null,2));
});
});
doc.end();
But then i got this error message:
{
Error
at new IppResponseError (/Users/alex/dev/print/printing/node_modules/ipp/lib/request.js:72:17)
at ClientRequest.<anonymous> (/Users/alex/dev/print/printing/node_modules/ipp/lib/request.js:40:8)
at Object.onceWrapper (events.js:293:19)
at emitOne (events.js:96:13)
at ClientRequest.emit (events.js:191:7)
at HTTPParser.parserOnIncomingClient [as onIncoming] (_http_client.js:522:21)
at HTTPParser.parserOnHeadersComplete (_http_common.js:99:23)
at Socket.socketOnData (_http_client.js:411:20)
at emitOne (events.js:96:13)
at Socket.emit (events.js:191:7)
name: 'IppResponseError',
statusCode: 400,
message: 'Received unexpected response status 400 from the printer',
stack: 'Error\n at new IppResponseError (/Users/alex/dev/print/printing/node_modules/ipp/lib/request.js:72:17)\n at ClientRequest.<anonymous> (/Users/alex/dev/print/printing/node_modules/ipp/lib/request.js:40:8)\n at Object.onceWrapper (events.js:293:19)\n at emitOne (events.js:96:13)\n at ClientRequest.emit (events.js:191:7)\n at HTTPParser.parserOnIncomingClient [as onIncoming] (_http_client.js:522:21)\n at HTTPParser.parserOnHeadersComplete (_http_common.js:99:23)\n at Socket.socketOnData (_http_client.js:411:20)\n at emitOne (events.js:96:13)\n at Socket.emit (events.js:191:7)' }
400 'response'
My printer does not support IPP, but i shared it on my Macbook, which provides an IPP service for all shared printers.
If i'm using the first paper tray and have paper in there everything is fine, but for my project it is necessary to print on other trays, too.
The attributes' list returned from Get-Printer-Attributes lists among other trays the second paper as supported media-source, but only the first paper tray works.
Does anyone have an idea how to print successfully on another paper tray?
Update: I also tried another printer, but i got the same error.
Update 22.06.17: It's still confused and don't have any clue how to fix this.
It appears that this pull request might be able to solve the issue you're having. Until the author of ipp merges the pull request, you can update your npm package to point to that patch by running the following in your project directory:
npm i --save ipp#github:jaymcaliley/ipp
The response to the request that you are sending is with the status code of 400 to the request that was issued to the printer.
This can be seen here on line 30.
This can be caused by a firewall configuration or wrong network setting.
You need to specify correctly the URL for the printer like in this example and to check if this URL is valid and the printer responds to it:
var printer = ipp.Printer("http://NPI977E4E.local.:631/ipp/printer");
It's been a while since i asked for help. Thanks to all for their contribution =)
I tried all suggested solutions from here and Github, but none of them worked, but I found a solution to solve my issue.
var ipp = require("ipp");
var PDFDocument = require("pdfkit");
var concat = require("concat-stream");
var doc = new PDFDocument;
doc.text("Hello World");
doc.pipe(concat(function (data) {
var printer = ipp.Printer("MY_URL");
var file = {
"operation-attributes-tag": {
"requesting-user-name": "admin",
'attributes-charset': 'utf-8',
'attributes-natural-language': 'de'
},
"printer-attributes": {
// OLD WAY WHICH DOES NOT WORK
//"media-col": {
// "media-source": "tray-2"
//},
},
// SOLUTION
"job-attributes-tag":{
"media": ["tray-2"]
},
data: data
};
printer.execute("Print-Job", file, function (err, res) {
console.log("Printed: " + res.statusCode);
});
}));
doc.end();
I tried this, because here (4.2.11) is media described with:
The values for "media" include medium-names, medium-sizes, input-
trays and electronic forms so that one attribute specifies the media.
I need to write a node.js application to keep checking if there is new email from the imap server.
I am trying to write an object handling the imap connection.
var Imap = require('imap'),
inspect = require('util').inspect;
const fs = require('fs');
var MailParser = require("mailparser").MailParser;
var Promise = require("bluebird");
function ImapConnection(config){
if (!(this instanceof ImapConnection))
return new ImapConnection(config);
this._imap = new Imap(config);
this._config = config;
}
ImapConnection.prototype.getImap = function(){
self = this;
if(this._imap.state !== 'authenticated'){
return new Promise(function(resolve,reject){
self._imap.connect();
self._imap.once('ready', function(){
resolve(self._imap);
});
});
}else{
return new Promise(function(resolve,reject){resolve(this._imap);});
}
}
But when I call the object after I called the end() function of the imap object it never connects again and always gives the timeout error:
{ [Error: Timed out while connecting to server] source: 'timeout' }
[connection] Closed
events.js:141
throw er; // Unhandled 'error' event
^
Error: Timed out while connecting to server
at null._onTimeout
(/home/ctw/Documents/nodejsmail/node_modules/imap/lib/Connection.js:280:15)
at Timer.listOnTimeout (timers.js:92:15)
Can anyone tell me what's wrong on my code or any other better practice? Thanks.
I am trying to send text to my network printer via tcp connection.
function print(buf2){
var printer = new net.Socket();
printer.connect(printer_port, printer_name, function() {
console.log('Connected');
printer.write(buf2);
printer.end()
});
}
Everything works fine, but after some time my application throws me the error Uncaught Error: connect ETIMEDOUT and it doesn't connect with my printer.
To fix it, I open a browser and navigate to my printers address(192.168.1.111) and then my application connects again but after some time it stops connecting and throws the same error (Uncaught Error: connect ETIMEDOUT).
The applications is written with electron and i use the net npm
var net = require('net');
In my application every 3 seconds i call a get request and then i call the print method
function proxy() {
var client = new HttpClient();
client.get('my_link', function(response) {
var jsonItem = JSON.parse(response)
if(jsonItem.items.length > 0)
{
var text_to_print = jsonItem.items[0].text
print(text_to_print,text_id);
}
Any suggestions what could cause this error?
This should help you to debug.
function print(printer_port, printer_name, buf2) {
var printer = net.createConnection(printer_port, printer_name, function () {
//'connect' listener
console.log("Connected!");
printer.end(buf2);
});
printer.setTimeout(60 * 1000); //1 minute
printer.on("end", function () {
console.log("Disconnected from server!");
});
printer.on("timeout", function () {
console.log("Timeout!");
printer.destroy();
});
}
I followed this tutorial (http://www.hongkiat.com/blog/node-js-server-side-javascript/) and when running the next to last script (for creating a static server) the command prompt says "Server running on port 8080", but when trying to access it at localhost:8080 I just get a webpage is unavailable error.
I have made an rule in the firewall to allow access to 8080 as well.
What could be causing this? Should i be trying to access the page from another address?
When I try to access the page i get the following error message in cmd:
C:\Users\id122302\Documents\test.js:11
path.exists(full_path,function(exists)
^
TypeError: undefined is not a function
at Server.<anonymous> (C:\Users\id122302\Documents\test.js:11:7)
at Server.emit (events.js:110:17)
at HTTPParser.parserOnIncoming [as onIncoming] (_http_server.js:491:12)
at HTTPParser.parserOnHeadersComplete (_http_common.js:111:23)
at Socket.socketOnData (_http_server.js:343:22)
at Socket.emit (events.js:107:17)
at readableAddChunk (_stream_readable.js:163:16)
at Socket.Readable.push (_stream_readable.js:126:10)
at TCP.onread (net.js:538:20)
This is my code:
var sys = require("sys");
my_http = require("http");
path = require("path");
url = require("url");
filesys = require("fs");
//Create Server
my_http.createServer(function(request,response)
{
var my_path = url.parse(request.url).pathname;
var full_path = path.join(process.cwd(),my_path);
path.exists(full_path,function(exists)
{
if (!exists)
{
response.writeHeader(404, {"Content-Type":"text/plain"});
response.write("404 Not Found\n");
response.end();
}
else
{
filesys.readFile(full_path, "binary", function(err,file)
{
if (err)
{
response.writeHeader(500,{"Content-Type":"text/plain"});
response.write(err + "\n");
response.end();
}
else
{
response.writeHeader(200);
response.write(file,"binary");
response.end();
}
});
}
});
}).listen(8080);
console.log("Server Running on 8080");
Your server shows an exception and a line number => go for that place !
As observed by #maniacnero, there's no more such thing as path.exists in the API. There's an fs.exists but it's been deprecated, to avoid abusive usage in node's concurrent context.
The feared scenario would be :
you check asynchronously if a file exists.
some other routine deletes/renames it in the meanwhile, or something else on the server does.
you think that the file exists so you try to open it and confidently don't handle the error case.
So the lessons learnt here are :
do things atomically
always deal with failures right away
Provided you stick to this discipline, there's no need for such thing as fs.exists. Here's a modified version of your code :
var sys = require("sys");
var http = require("http");
var path = require("path");
var url = require("url");
var fs = require("fs");
var port = 8080;
http.createServer(function(request,response) {
var my_path = url.parse(request.url).pathname;
var full_path = path.join(process.cwd(),my_path);
fs.readFile(full_path, function(err, file) {
if (err) {
response.writeHeader(404, {"Content-Type":"text/plain"});
response.write("404 Not Found\n");
response.end();
} else {
response.writeHeader(200);
response.write(file);
response.end();
}
});
}).listen(port);
console.log("Server Running on " + port);
I also removed those "binary" thingys, that are way outdated and not documented in the API either !
Playing around with sample code is a nice way to learn, but only if you don't do it blindly. ;) Especially in a weakly typed language building on a fast changing API and where myriads of tutorials have been written by utter beginners. This is your friend : https://nodejs.org/api/
I have a node js server, and a html/javascript client.
I simply want to allow the client to send a json-string to the node.js server, the server process's that string and returns a result string back to the client.
I started by setting up the html-client to call like so :
var msg =
{
type: "message",
text: "Hello"
};
function CallWebSocket()
{
var socket = new WebSocket("ws://127.0.0.1:8080","test");
socket.onopen = function (event)
{
alert(JSON.stringify(msg));
socket.send(JSON.stringify(msg));
};
socket.onmessage = function(event)
{
alert(event.data);
}
}
and node.js :
var net = require('net');
var server = net.createServer(function(socket)
{
// do what you need
socket.setEncoding("utf8");
socket.on('data', function(data)
{
var jsonData = JSON.parse(data);
socket.write(jsonData.text);
socket.end();
process.exit(0);
});
});
server.listen(8080);
but on the server I get this error :
undefined:1
``GET / HTTP/1.1
^
SyntaxError: Unexpected token G
at Object.parse (native)
at Socket.<anonymous> (/home/jay/projects/nodejs/test/json-server.js:8:23)
at Socket.EventEmitter.emit (events.js:95:17)
at Socket.<anonymous> (_stream_readable.js:746:14)
at Socket.EventEmitter.emit (events.js:92:17)
at emitReadable_ (_stream_readable.js:408:10)
at emitReadable (_stream_readable.js:404:5)
at readableAddChunk (_stream_readable.js:165:9)
at Socket.Readable.push (_stream_readable.js:127:10)
at TCP.onread (net.js:526:21)
Any help is much appreciated.
UPDATE
The updated server code :
var WebSocketServer = require('websocket').server;
var http = require('http');
var server = http.createServer(function(request, response) {
console.log((new Date()) + ' Received request for ' + request.url);
response.writeHead(404);
response.end();
});
server.listen(8080, function() {
console.log((new Date()) + ' Server is listening on port 8080');
});
wsServer = new WebSocketServer({
httpServer: server,
// You should not use autoAcceptConnections for production
// applications, as it defeats all standard cross-origin protection
// facilities built into the protocol and the browser. You should
// *always* verify the connection's origin and decide whether or not
// to accept it.
autoAcceptConnections: false
});
function originIsAllowed(origin) {
// put logic here to detect whether the specified origin is allowed.
return true;
}
wsServer.on('request', function(request) {
if (!originIsAllowed(request.origin)) {
// Make sure we only accept requests from an allowed origin
request.reject();
console.log((new Date()) + ' Connection from origin ' + request.origin + ' rejected.');
return;
}
var connection = request.accept('echo-protocol', request.origin);
console.log((new Date()) + ' Connection accepted.');
connection.on('message', function(message) {
if (message.type === 'utf8') {
console.log('Received Message: ' + message.utf8Data);
connection.sendUTF(message.utf8Data);
}
else if (message.type === 'binary') {
console.log('Received Binary Message of ' + message.binaryData.length + ' bytes');
connection.sendBytes(message.binaryData);
}
});
connection.on('close', function(reasonCode, description) {
console.log((new Date()) + ' Peer ' + connection.remoteAddress + ' disconnected.');
});
});
This solved my problem and I am now getting the message back.
A websocket is not a plain TCP socket. That is basically the core of your problem.
The websocket protocol looks like a modified HTTP protocol that allows two way communication using a single (TCP) socket. Read the RFC for more info on how the websocket protocol actually works: https://www.rfc-editor.org/rfc/rfc6455#section-1.2
You have two options if you want to use websockets with node servers:
Read the RFC and write a function to handle the websocket protocol so you can pass that function to socket.on.
Use a websocket server module that someone else have written. Go to npm and search for "websocket server" or google "websocket server npm". There are lots of modules out there. Pick one you like best.
There is a third alternative. Use socket.io. Socket.io is a library that communicates between client and server using websocket if possible (preferred) but is able to degrade to other transports such as Flash and ajax on older browsers.