Node JS - Use Printer (Hardware) - angularjs

I'm developing an application with Angular JS and Node JS where I need to see all available printers in the user's machine, let the user select one of them and print a receipt.
Is there a way to achieve this?

I did an application like that.. I did it using http://nwjs.io/ and the module in the comment: https://www.npmjs.com/package/printer, here is a working code with this module printing raw in the default printer a file:
var printer = require('printer');
var fs = require('fs');
var info = fs.readFileSync('ticket.txt').toString();
function sendPrint() {
printer.printDirect({
data: info,
type: 'RAW',
success: function (jobID) {
console.log("ID: " + jobID);
},
error: function (err) {
console.log('printer module error: '+err);
throw err;
}
});
}
sendPrint();
you can adapt it to use the getPrinters() method to enumerate all installed printers and then allow the user to select the desired one.

Related

Displaying a var using AngularJS/HTML on the screen

I'm using MEAN Stack to construct my web application. (Mongo, Express, Angular, NodeJS) I have a server.js file, html file and a css file. My server.js generates a var number which I want to get rendered on the frontend, however I'm having some trouble doing that. Let me explain, on my html there a button I created, whenever the user clicks on that button, I want this specific var to be shown the screen, but it doesn't work.
Here is the code for the creation of the button:
Some Text
Below is the angularjs code for where I use the exact rendering to be occurred:
The Amount:
{{links.amountLinks}}
test this
My server.js code:(Please note I'm using jsdom module)
var jsdom = require("jsdom");
jsdom.env(
url,
["http://code.jquery.com/jquery.js"],
function (err, window) {
// console.log("there have been", window.$("a").length, "io.js releases!");
// alert("there have been", window.$("a").length, "io.js releases!");
console.log(window.$("a").length);
amountLinks = window.$("a").length;
json.amountLinks = amountLinks;
data = amountLinks;
});
Does anyone know how I can fix this?
The code can be fixed as follow:
jsdom.env(
url,
["http://code.jquery.com/jquery.js"],
function (err, window) {
// console.log("there have been", window.$("a").length, "io.js releases!");
// alert("there have been", window.$("a").length, "io.js releases!");
console.log(window.$("a").length);
amountLinks = window.$("a").length;
json.amountLinks = amountLinks;
data = amountLinks;
res.send(JSON.stringify(json, null, 4))
});
}

Is there a way to dump a thousand images somewhere and extract them using REST Api?

Here is the thing:-
I have over a thousand images saved locally in my mac. I have a landing page that mocks an ecommerce deal site. It would be tedious to have to manually type in the src url in the img tag for a thousand pictures. Thus, i thought i could somehow have this images dumped in a cloud storage or something and use REST api get method to extract these images in a response.data. Then assign it to a $scope variable and use ng-repeat to bind the images in my landing page view. Is this possible? If not, what are the alternatives? SQL database?
Appreciate your help. P.S. I am totally a beginner at web development.
Install node.js. It's Javascript for a server which should make it pretty easy since you already know Javascript.
On a Mac, you can install node like this:
brew install node
Use this node.js code (credit to codepedia.com, tweaked a little by me):
//include http, fs and url module
var http = require('http'),
fs = require('fs'),
path = require('path'),
url = require('url');
imageDir = './images/';
//create http server listening on port 3333
http.createServer(function (req, res) {
//use the url to parse the requested url and get the image name
var query = url.parse(req.url,true).query;
pic = query.image;
if (typeof pic === 'undefined') {
getImages(imageDir, function (err, files) {
var imageList = JSON.stringify(files);
res.writeHead(200, {'Content-type':'application/json'});
res.end(imageList);
});
} else {
//read the image using fs and send the image content back in the response
fs.readFile(imageDir + pic, function (err, content) {
if (err) {
res.writeHead(400, {'Content-type':'text/html'})
console.log(err);
res.end("No such image");
} else {
//specify the content type in the response will be an image
res.writeHead(200,{'Content-type':'image/jpg'});
res.end(content, "binary");
}
});
}
}).listen(3333);
console.log("Server running at http://localhost:3333/");
//get the list of jpg files in the image dir
function getImages(imageDir, callback) {
var fileType = '.jpg',
files = [], i;
fs.readdir(imageDir, function (err, list) {
for(i=0; i<list.length; i++) {
if(path.extname(list[i]) === fileType) {
files.push(list[i]); //store the file name into the array files
}
}
callback(err, files);
});
}
Run this from the command line to start you new image server (assuming you named the file "server.js"):
node server.js
You should see this text appear on the command line:
Server running at http://localhost:3333/
You can quickly test it by going to this address in your browser and you should see a JSON object showing you an array of all the filenames in the "./images" directory. By the way, this program assumes you're putting the images folder in the same directory as "server.js". You can put the images directory anywhere and just change the path of the variable "imageDir".
Now you can load the list of files from Angular using this code in your controller:
$http.get("http://localhost:3333", function(data) {
$scope.images = data;
});
In your view, you can now use an ng-repeat like this to display all the images:
<div ng-repeat="image in images" style="padding: 8px">
<img src="http://localhost:3333/image={{ image }}">
</div>
Note: this will work if you run it locally on your Mac or if you upload all the images to a server on which you can use Node.js.

How to edit server stored JSON file with NodeJS

I have a web server hosting over localhost. The website I am accessing is a "Todo list app" written with AngularJS. To load the todo's, the browser gets a JSON file with the information. An example of this:
[
{"name":"Clean the house"},
{"name":"Water the dog"},
{"name":"Feed the lawn"},
{"name":"Pay dem bills"},
{"name":"Run"},
{"name":"Swim"}
]
It then loops through all the items and "prints" them out onto the website. I have various options like "Save" and "Delete". They work client-side, but that way does not allow me to properly save them, as when the browser is refreshed, all the content is reset with the server's static JSON file.
I was wondering if there was some way of using NodeJs to host the website and listen for incoming AJAX request and edit the content in the file based off that.
Writing a file asynchronously in nodejs can be done as follows.
var fs = require('fs');
var fileName = './file.json';
var file = require(fileName);
file.key = "new value"; // This will be coming as a http POST method from your view
fs.writeFile(fileName, JSON.stringify(file), function (err) {
if (err) return console.log(err);
console.log(JSON.stringify(file));
console.log('writing to ' + fileName);
});
The caveat is that json is written to the file on one line and not prettified. ex:
{
"key": "value"
}
will be...
{"key": "value"}
To avoid this, simply add these two extra arguments to JSON.stringify
JSON.stringify(file, null, 2)
null - represents the replacer function. (in this case we don't want to alter the process)
2 - represents the spaces to indent.
NodeJS does not persist data out of the box.
You want something like NodeJS + Express and special CRUD routes like POST for creating items or DELETE for deleting them.
In this routes you have to add a data persistance layer like mongoose if you want to use MongoDB or Sequelize if you want to add a SQL database behind it.
Each of this ORM requires to specify a Datamodel which can be saved.
Here an example for a mongoose implementation:
'use strict';
/**
* Module dependencies.
*/
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var plugins = require('./model.server.plugins');
/**
* Customer Schema
*/
var CustomerSchema = new Schema({
name: {
type: String,
default: '',
required: 'Please fill a name',
trim: true
},
created: {
type: Date,
default: Date.now
}
});
mongoose.model('Customer', CustomerSchema);
Here is the controller
'use strict';
/**
* Module dependencies.
*/
var mongoose = require('mongoose'),
errorHandler = require('./errors.server.controller'),
Customer = mongoose.model('Customer'),
_ = require('lodash');
/**
* Create a Customer
*/
exports.create = function(req, res) {
var customer = new Customer(req.depopulated);
customer.user = req.user;
customer.save(function(err) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.jsonp(customer);
}
});
};
Here the route
router.route('/')
.post(customers.create);

Why won't this code work to create a Parse object in an Ionic app?

I'm trying to create a Parse object in an app using the Ionic Framework, and I can't get it to work. I'm fairly new to programming, but I've been able to create Parse users, just not objects. Can anyone help me find a solution? Please see the code below for my controller in question. Thanks!
.controller('AddProspectsController', function($scope, $state, $rootScope) {
if (!$rootScope.isLoggedIn) {
$state.go('welcome');
}
$scope.prospect = {};
$scope.error = {};
// Syntax to create a new subclass of Parse.Object.
//var Prospects = Parse.Object.extend("Prospects");
$scope.addProspect = function() {
// Create a new instance of that class.
var Prospects = Parse.Objext.extend("Prospects");
var prospects = new Prospects();
prospect.set("name", $scope.prospect.name);
prospect.set("phone", $scope.prospect.phone);
prospect.set("email", $scope.prospect.email);
prospect.set("interest", $scope.prospet.interest);
prospect.save(null, {
success: function(prospect) {
// Execute any logic that should take place after the object is saved.
$state.go('app.prospects', {clear: true});
alert('New object created with objectId: ' + prospect.id);
},
error: function(prospect, error) {
// Execute any logic that should take place if the save fails.
// error is a Parse.Error with an error code and message.
alert('Failed to create new object, with error code: ' + error.prospect);
}
});
}
})
You have another spelling error on this line:
var Prospects = Parse.Objext.extend("Prospects");
This is not Objext, but Object.​​​​​​
I hope this will help.
There is a spelling error... you have the variable named prospects with an "s" and when you are creating the object, you are using a variable named prospect

Design pattern for shared database handle in Node.JS

How do I share a database connection across various NodeJS modules? The example I have found all had a monolithic structure where the entire code was in one single app.js file.
/* main.js */
var foo = require("./foo");
/* express stuff ...*/
mysql = /* establish mysql connection */
app.get("/foo", foo.hello );
/* foo.js */
exports.hello = function(req, res) {
res.send("Hello from the foo module!");
}
How would I access "mysql" from my module "foo"? What is the recommended design pattern for this?
You can use the module pattern to easily pass your db object (and anything else) to modules that need it.
// users.js
module.exports = function( options ) {
var db = options.db;
var pants = options.pants; // or whatever
return {
GetUser: function( userID, callback ) {
db.query("....", function (err, results) {
callback(results)
});
},
AnotherFunc: function (...) {},
AndAnotherFunc: function (...) {}
};
};
You use this module like:
// make your db connection here
var users = require('./users.js')({
db: db,
pants: 'blue'
});
users.GetUser( 32, function( user ) {
console.log("I got the user!");
console.log( user );
});
I find this to be a great way to write modules, as it's a lot like making an actual Class object, like in C++. You can even simulate 'private' methods/parameters.
I usually put mysql handle in a different file (module) and require the module in different routes.
I believe you also have to connect to mysql asynchronously, you can refer to this question, which uses a callback function to solve the problem.

Resources