Ok, so I'm trying to print from a webpage (the typical "print" button, but I don't want the print dialog to appear) so I decided to use my already existing node.js backend to do the task (mainly because printing from browser is nearly impossible without the printing dialog).
I found the node-printer (https://github.com/tojocky/node-printer) module, and it works great, but only with text. I tried to send RAW data, but what it does is printing the raw characters. What I actually need is to print a logo, along with some turn information (this is for a customer care facility).
Also, the printer must be installed locally, so I can't use IPP.
Is there any way to print an image, or a combination of images and text with node.js? can it be done through node-printer or is there another way?
I ended calling an exe to do the work for me. I use a child_process to call printhtml, which does all the printing work for me. My code ended this way:
var exec = require('child_process').exec;
exec('printhtml.exe file=file.html', function(err, data) {
console.log(data.toString());
});
Actually, you can print image using node-printer. This work for me
var Printer = require('node-printer');
var fs = require('fs');
// Get available printers list
var listPrinter = Printer.list();
// Create a new Pinter from available devices
var printer = new Printer('YOUR PRINTER HERE. GET IT FROM listPrinter');
// Print from a buffer, file path or text
var fileBuffer = fs.readFileSync('PATH TO YOUR IMAGE');
var jobFromBuffer = printer.printBuffer(fileBuffer);
// Listen events from job
jobFromBuffer.once('sent', function() {
jobFromBuffer.on('completed', function() {
console.log('Job ' + jobFromBuffer.identifier + 'has been printed');
jobFromBuffer.removeAllListeners();
});
});
I had success with the Node IPP package https://www.npmjs.com/package/ipp.
The example code on the docs, which uses another node module PDFKIT to convert your html/file into a PDF, does not work. See my answer here: Cannot print with node js ipp module for a working example.
Related
Okay so basically I'm trying to create a typing game that uses a JSON file as the database. I'm using Nodejs to manipulate the use of a .json file with the fs module. What I want to do is have a main.js which operates the website's appearance which will contain a table of high scores, and I also want a player.js which will run on the back-end which updates a JSON file containing each player's name and high score.
So I was experimenting with it. I learned the hard way that require() is a node function. I want main.js to call a function from player.js and send it parameters.
var playerArr = player.updatePlayers("Rain", 30);
I know this doesn't work but the updatePlayers() function written with node in player.js returns an array and I want to set it to playerArr within main.js.
require() comes up with an error in the browser because its not a part of vanilla Javascript and I know it has to be run on a node server.
Is there any way to do this? It's for a school project and I'd love to be able to implement Nodejs and JSON into it.
Okay so everything's working except one crucial thing... the array isn't being sent back to the browser. I decided to use routes from express:
app.get("/:name,:score", returnScoreboard);
function returnScoreboard(request, response){
let data = request.params;
playerArr = updatePlayers(data.name, data.score);
response.send(playerArr);
}
Now in my main.js, this is my code:
var playerArr;
var updatePlayer = new XMLHttpRequest();
updatePlayer.onreadystatechange = () => {
playerArr = this.responseText;
}
updatePlayer.open("GET", "/Moo,100", true);
updatePlayer.send();
console.log(playerArr);
And I can't seem to get a response from into the playerArr. The JSON file that I'm using is getting updated correctly with a new object every time ({"name":"Moo", "score":100}) but it's not being assigned to playerArr. Please help!
I suggest you have a Node backend and use something like https://expressjs.com/. You can use it to set up some endpoint(s). These endpoints would be called upon by your frontend JS code using Fetch or something of the like, https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch.
Response to the edits above:
I think you are probably facing an asynchronous issue. I just moved the console.log into the onreadystatechange call. The onreadystatechange executes whenever a response comes back from the server, so by the time your code got to the original console.log the onreadystatechange may not have fired.
var playerArr;
var updatePlayer = new XMLHttpRequest();
updatePlayer.onreadystatechange = () => {
playerArr = this.responseText;
console.log(playerArr);
}
updatePlayer.open("GET", "/Moo,100", true);
updatePlayer.send();
I am working with Angular 5, I have an application in which I need to read an AMP HTML file as text. This file is contained in a component and should only be accessed from this component.
I would like to be able to open the file in read-only by giving its name.
I'm actually searching for something like this:
let file = open('amp.html');
Is it possible? If not how can I do to achieve this?
If you're writing browserside JS
You can't just simply read a file. The JS is running on your browser, and you need to think about where you're getting that file from.
If the file is on a server, you need to fetch that file from the server first by making a request for it.
If you're reading a file on the user's computer, you're gonna be using the File API on the browser to allow the user to select that file.
If you're writing backend JS
Assuming you're using NodeJS, you can conduct file operations like you would with other programming languages. Check out the fs module
If i understand you correct, you can read it as text like this:
function readFile(file){
var raw = new XMLHttpRequest(); // create a request
raw.open("GET", file, false); // open file
raw.onreadystatechange = function (){ // file is ready to read
if(raw.readyState === 4){
if(raw.status === 200 || raw.status == 0){
var allText = raw.responseText;
alert(allText); // can be also console.logged, of course.
}
}
}
raw.send(null); // return control
}
usage:
readFile('link.html')
I solved this issue thankfully to this question.
Basically, I want to use this feed:
var feedParser = require('ortoo-feedparser')
var url = "http://iwnsvg.com/feed";
feedParser.parseUrl(url).on('article', function(article) {
console.log('title; ', article.title);
});
to show all news feeds in my HTML web page. However, I'm using node.js to run the web server at (localhost:8080). I have a separate file for the web server (index.html, style.css and client.js).
Instead of using console.log to show the news feed, I want it to appear on my webpage in my text area called alltext which is in the index.html, instead of it being printed to the console.
You can do it via various ways two of them are being mention below :
Using Sockets
var io = require('socket-io');
var feedParser = require('ortoo-feedparser')
var url = "http://iwnsvg.com/feed";
feedParser.parseUrl(url).on('article', function(article) {
io.emit('article', article.title);
console.log('title; ', article.title);
});
Now you can listen article event on webpage and display your result.
Now, Second way is traditional one. You have to save the feeds in DB and then use api to get all The Feeds you saved earlier in DB.
Thanks
I have app on Heroku and I want to capture webpage and save as image or base64. Problem is: I have node.js script in that app and I want to use phantomjs, but phantom is not compatible with node.
So, I need to capture webpage and save output (image or base64 string) to variable so my primary (node) app can use that values.
I tried this but I can't figure how to use that: https://www.npmjs.com/package/phantom
This is what I have so far: (source)
app.get('/capture', function(request, response) {
var phantom = require('phantom');
phantom.create().then(function(ph) {
ph.createPage().then(function(page) {
page.open('https://stackoverflow.com/').then(function(status) {
console.log(status);
page.property('content').then(function(content) {
var base64 = page.renderBase64('PNG');
console.log(base64);
page.close();
ph.exit();
});
});
});
});
});
What I need on my heroku server (beside already installed node), what I need to install in node.js, how to use all that?
Thanks.
So: send request to capture page -> make image -> pass output to JS variable
I'm working on a PhoneGap application that captures images using the camera and, later, uploads them. There are two modes of operation for camera in PhoneGap: raw base64 encoded data or a file URI.
The docs themselves say:
Note: The image quality of pictures taken using the camera on newer
devices is quite good. Encoding such images using Base64 has caused
memory issues on some of these devices (iPhone 4, BlackBerry Torch
9800). Therefore, using FILE_URI as the 'Camera.destinationType' is
highly recommended.
So I'm keen to use FILE_URI option. This works great and you can even show the images in IMG tags. The URL looks like this:
file://localhost/var/mobile/Applications/4FE4642B-944C-449BB-9BD6-1E442E47C7CE/tmp/photo_047.jpg
However, at some point later I want to read the contents of the file to upload to a server. I was going to do this using the FileReader type. This doesn't work and I think it's because I can't access the file at the URL above.
The error code I get back from readDataUrl is 1 > FileError.NOT_FOUND_ERR = 1;
Any ideas how I can get to the file? I tried just accessing the last part of the path (photo_047.jpg) based on another sample I saw but no luck.
I'm just getting started with PhoneGap, and given the age of this question you may have found an answer already, but I'll give it a try anyway.
First, would you be able to use the built-in FileTransfer object? It takes a file: URI as an argument.
If FileTransfer won't work for you, and you need to read the file data yourself, you'll need the PhoneGap File objects, like FileReader , as you said. But most of those expect a plain pathname -- not a URI -- to specify the file to work with. The reason you're getting NOT_FOUND_ERR is because it's trying to open a file named file:/localhost/var....
Here's a quick one-liner to extract the path part from your URI:
var path = /file:\/\/.*?(\/.*)/.exec(fileuri)[1];
Hope this helps!
The answer from jgarbers was of help to me but it did not solve the problem. I realized the camera stores photos in Temp folder instead of Document folder. Setting my local file system to temporary allowed it to find the correct location for the camera images.
window.requestFileSystem(LocalFileSystem.TEMPORARY, 0, ...
...
window.requestFileSystem(LocalFileSystem.TEMPORARY, 0, ...
...
var path = /file://.?(/.)/.exec(fileuri)[1];
Ref. above jgarbers and Rik answers (solution has been tested successfully on iOs 7)
you can user the file transfer plugin for uploading any file to the server.
//// pass your file uri to the mediafie param
function uploadFile(mediaFile) {
var ft = new FileTransfer();
path = mediaFile.fullPath;
name = mediaFile.name;
////your service method url
var objUrl = http://example.com;
ft.upload(path,
objUrl,
function (result) {
alert("Success");
},
function (error) {
alert('Error uploading file ' + path + ': ' + error.code);
},
{ fileName: name });
}