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.
Related
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)
I have a large JSON file (~1 GB) that I am trying to work with. It is comprised of dates and cities. Ultimately my goal is to get an summary of the data: for each year, how many entries of each city do I have?
In the command window I run type myjson.json |node --max-old-space-size=5120 script.js where script.js is:
var JSONStream = require('JSONStream')
, es = require('event-stream'), fs = require('fs');
process.stdin
.pipe(JSONStream.parse('*'))
.pipe(es.mapSync(function (data) {
if (data.date == '1972'){
fs.createWriteStream('file_1972.txt');
}
}
));
I am getting this error:
Error: EMFILE: too many open files, open 'file_1972.txt' at Error (native)
The process tried to write to a nonexistant pipe.
What is this error all about and how do I fix it? Is there something wrong in my approach / code?
Solution:
var JSONStream = require('JSONStream')
, es = require('event-stream'), fs = require('fs');
var stream1 = fs.createWriteStream('file_1972.txt');
process.stdin
.pipe(JSONStream.parse('*'))
.pipe(es.mapSync(function (data) {
if (data.date == '1972'){
stream1.write(data.date + data.city)
}
}
));
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 client which downloads and decrypts an AES encrypted file from another host.
var base64 = require('base64-stream');
var crypto = require('crypto');
var aes = crypto.createDecipher('aes-256-cbc', crypto.createHash('sha256').update(pass).digest('hex'));
// file stream
var file = fs.createWriteStream(params.target);
var base64reader = base64.decode();
response.pipe(base64reader) // decode base64
.pipe(aes) // decrypt
.pipe(file); // write in file
// on last data chunk received: file load complete
aes.on('end', function (chunk) {
if (typeof params.success !== 'undefined')
params.success();
});
If the other host close his connection unexpectedly before finishing the request, the code above throws this error:
TypeError: error:0606506D:digital envelope routines:EVP_DecryptFinal_ex:wrong final block length
at Decipher.Cipher._flush (crypto.js:262:27)
at Decipher.eval (_stream_transform.js:130:12)
at Decipher.g (events.js:187:16)
at Decipher.EventEmitter.emit (events.js:95:17)
at prefinish (_stream_writable.js:427:12)
at finishMaybe (_stream_writable.js:435:7)
at afterWrite (_stream_writable.js:317:3)
at onwrite (_stream_writable.js:307:7)
at WritableState.onwrite (_stream_writable.js:100:5)
at afterTransform (_stream_transform.js:99:5)
at TransformState.afterTransform (_stream_transform.js:74:12)
at Decipher.Cipher._transform (crypto.js:258:3)
at Decipher.Transform._read (_stream_transform.js:179:10)
at Decipher.Readable.read (_stream_readable.js:334:10)
at flow (_stream_readable.js:743:26)
at WriteStream.eval (_stream_readable.js:601:7)
I tried to add an aes.on('error', function(() {...}); handler but it will not be called. I also tried adding
response.on('end', function() { aes.emit('close'); });
response.on('close', function() { aes.emit('close'); });
but then aes.on('end', ...); will not be called. Adding aes.emit('end') to this statements make no sense, because this will be also called in case of an error which leads to the error above.
response.on('end', function() { aes.emit('end'); aes.emit('close'); });
response.on('close', function() { aes.emit('end'); aes.emit('close'); });
Does anybody have an idea how I can catch this error?
Thanks a lot!!
Its a bug in node.js v0.11.9 which is solved in v0.11.13. Then aes.on('error', ...) will be called correctly.
I am trying to find the id of clients that connect to my socket.io/node.js server using the method described in the top answer here how to get session id of socket.io client in Client but when I do I get the error message
C:\Games\My games\Newserver\Server\server.js:5
playerlist[playerlist.length+1] = [client.id,username]
^
ReferenceError: client is not defined
at SocketNamespace.<anonymous> (C:\Games\My games\Newserver\Server\server.js
:5:37)
at SocketNamespace.EventEmitter.emit [as $emit] (events.js:117:20)
at connect (C:\Games\My games\Newserver\Server\node_modules\socket.io\lib\na
mespace.js:292:10)
at C:\Games\My games\Newserver\Server\node_modules\socket.io\lib\namespace.j
s:308:13
at SocketNamespace.authorize (C:\Games\My games\Newserver\Server\node_module
s\socket.io\lib\namespace.js:252:5)
at SocketNamespace.handlePacket (C:\Games\My games\Newserver\Server\node_mod
ules\socket.io\lib\namespace.js:302:14)
at Manager.handleClient (C:\Games\My games\Newserver\Server\node_modules\soc
ket.io\lib\manager.js:698:32)
at Manager.handleUpgrade (C:\Games\My games\Newserver\Server\node_modules\so
cket.io\lib\manager.js:618:8)
at Server.<anonymous> (C:\Games\My games\Newserver\Server\node_modules\socke
t.io\lib\manager.js:123:10)
at Server.EventEmitter.emit (events.js:106:17)
My code is as follows
var io = require('socket.io').listen(1337); //Tells server to use socket.io and to listen on port 1337
var playerlist= new Array(); //Array to store player usernames & client ids of these players
io.sockets.on("connection", function(socket) {
playerlist[playerlist.length+1] = [client.id,username] //Writing to array, crashes here at client.id
socket.on("username", function(data) {
var str = "[Server] User "
var str2 = data
var str3 = " connected."
var finalstr = str.concat(str2.concat(str3))
socket.broadcast.send(finalstr)
socket.send("[Server] Connected")
});
});
Does anyone know how to fix this? I can only assume I haven't require()d something that I should have but I don't know what.
You've got no variable client. Use socket instead.
Change the line
playerlist[playerlist.length+1] = [client.id,username]
to
playerlist[playerlist.length] = [socket.id,username]
By the way, I think you should use playerlist.length here.