send PDF file using websocket node.js - javascript

I have the following server:
var pvsio = require("./pvsprocess"),
ws = require("ws"),
util = require("util"),
http = require("http"),
fs = require("fs"),
express = require("express"),
webserver = express(),
procWrapper = require("./processwrapper"),
uploadDir = "/public/uploads",
host = "0.0.0.0",
port = 8082,
workspace = __dirname + "/public",
pvsioProcessMap = {},//each client should get his own process
httpServer = http.createServer(webserver),
baseProjectDir = __dirname + "/public/projects/",
PDFDocument = require ("pdfkit");
var p, clientid = 0, WebSocketServer = ws.Server;
...
var wsServer = new WebSocketServer({server: httpServer});
wsServer.on("connection", function (socket) {
var socketid = clientid++;
var functionMaps = createClientFunctionMaps();
socket.on("message", function (m) {
Is possible send a pdf file to the client inside socket.on("message" .. function ?
I can send message using send(), there is some function to send files?
Thanks

I would just send the pdf in binary.
fs.readFile(something.pdf,function(err,data){
if(err){console.log(err)}
ws.send(data,{binary:true});
}
And at the client side, I would create a blob and an object url from the received binary data. From this onward, you can pretty much do anything, says open the pdf file in a new window/tab.
conn.onmessage = function(e){
pdfBlob = new Blob([e.data],{type:"application/pdf"});
url = webkitURL.createObjectURL(pdfBlob);
window.open(url);
}
Hope this help.

Related

error 403 on nodejs when running .js file

help pls, I am trying to do a POST on my api but I am getting error 403, I read many topics but still not resolved my problem.
I am running my js file on nodejs prompt using comand: node myfilename.js to compile and getting this error. below is my code. I was supposed to get a json file back from the site I am trying to consume.
var app = require('./config/customs-express')();
var unirest = require('unirest');
var crypto = require('crypto');
var qs = require('querystring');
app.listen(3000, function() {
console.log('Server running door 3000');
});
var MB_TAPI_ID = 'xxx';
var REQUEST_HOST = 'https://www.xxxx.net';
var REQUEST_PATH = '/tapi/v3';
var MB_TAPI_SECRET = 'xxx';
var tapi_nonce = Math.round(new Date().getTime() / 1000);
var tapi_method = 'list_orders';
var params = (tapi_method, tapi_nonce);
var params_string = ((REQUEST_PATH) + '?' + (params));
var tapi_mac = crypto.createHmac('sha512', MB_TAPI_SECRET)
.update(tapi_method + ':' + MB_TAPI_SECRET + ':' +
tapi_nonce)
.digest('hex');
unirest.post(REQUEST_HOST)
.headers({'Content-type': 'application/x-www-form-urlencoded'})
.headers({'Key': MB_TAPI_ID})
.headers({'Sign': tapi_mac})
.send(qs.stringify({'method': tapi_method, 'tonce': tapi_nonce}))
.send(qs.stringify(params_string))
.end(function (response) {
console.log(response.body);
});
var app = require('./config/customs-express')();
var unirest = require('unirest');
var crypto = require('crypto');
var qs = require('querystring');
app.listen(3000, function() {
console.log('Server running door 3000');
});
403 means forbidden. The API is telling you "no."
If this works when you visit the page, it probably means they are using cookies. If that is the case, first hit the login page, get a cookie, then send the login request with the cookie. Superagent can do this, for example.

download file from url to server using node.js

I need a requirement to download file from any url to the server that running the app. I used the following code in Node.js. And its working in the case of localhost. But not in the case of server.
var express = require('express');
var app = express();
var http = require('http');
var https = require('https');
var request = require('request');
var fs = require('fs');
var path = require('path');
app.get('/', function( request, response ){
response.send('connection established...!');
});
app.get('/download', function(request, response){
var file = "https://c1.staticflickr.com/6/5219/5450451580_7f066f7868_b.jpg";
var filename = path.basename( file );
var ssl = file.split(':')[0];
var dest = __dirname +'downloads/'+ filename;
var stream = fs.createWriteStream( dest );
if ( ssl == 'https') {
https.get( file, function( resp ) {
resp.pipe( stream );
response.send('file saved successfully.*');
}).on('error', function(e) {
response.send("error connecting" + e.message);
});
} else {
http.get( file, function( resp ) {
resp.pipe( stream );
response.send('file saved successfully.*');
}).on('error', function(e) {
response.send("error connecting" + e.message);
});
}
});
app.listen(process.env.PORT || 3000);
do you have write privileges to the server(assuming your local is mac/windows and server is a linux box)? if not assign the privileges

How to make the websocket server be at a router?

I'm writing a websocket server using nodejs-ws module, but the server can only be at the root of the server, so how I can make it at a child router like localhost:3000/chat?
I need your help, thanks a lot!
Working example:
var ws = require('ws');
var http = require('http');
var httpServer = http.createServer();
httpServer.listen(3000, 'localhost');
var ws1 = new ws.Server({server:httpServer, path:"/chat"});
ws1.on('connection', function(){
console.log("connection on /chat");
});
var ws2 = new ws.Server({server:httpServer, path:"/notifications"});
ws2.on('connection', function(){
console.log("connection on /notifications");
});
could you please tell me how to use this in express?
To route websockets with Express I'd rather use express-ws-routes
var express = require('express');
var app = require('express-ws-routes')();
app.websocket('/myurl', function(info, cb, next) {
console.log(
'ws req from %s using origin %s',
info.req.originalUrl || info.req.url,
info.origin
);
cb(function(socket) {
socket.send('connected!');
});
});

Node.js file transfer using UDP

I'm trying to create a simple Node.js server that receives files from clients via UDP. The problem I'm having is that every time I try to transmit a large file (anything over 100kb), the server doesn't seem to respond. So far I've been successful at transmitting files up to 50kb.
Is there any way to resolve this issue?
Client Code:
var PORT = 33333;
var HOST = 'localhost';
var dgram = require('dgram');
var log = require('sys').log;
var client = dgram.createSocket('udp4');
var fs = require("fs");
fs.readFile('C:\\test.pdf', function (err,data) {
if (err) {
return console.log(err);
}
client.send(data, 0, data.length, PORT, HOST, function(err, bytes) {
if (err)
throw err;
log('UDP file sent to ' + HOST +':'+ PORT);
log('File sise: ' + data.length);
});
});
Server Code:
var PORT = 33333;
var HOST = 'localhost';
var dgram = require('dgram');
var server = dgram.createSocket('udp4');
var fs = require("fs");
var log = require('sys').log;
var wstream = fs.createWriteStream('test.pdf');
wstream.on('finish', function () {
console.log('file has been written');
});
server.on('message', function (message, remote) {
wstream.write(message);
wstream.end();
});
server.bind(PORT, HOST);
From the dgram docs:
The Payload Length field is 16 bits wide, which means that a normal payload cannot be larger than 64K octets including internet header and data (65,507 bytes = 65,535 − 8 bytes UDP header − 20 bytes IP header); this is generally true for loopback interfaces, but such long datagrams are impractical for most hosts and networks.
You can't send datagrams of more than 65,507 bytes. That's a hard limit on UDP. It sounds like you should be using a higher-level protocol for these files.

Javascript create object with data structure like this

I would like to create an object with a similar data structure if possible.
Must I create a new object for every player? Could somebody tell me how?
players
players.name='John'
players.John.age='12'
players.John.adress='London ..'
players.John.telnumber='09876587655'
edit1
Sorry I know this is the basic. I just ask one more question an them i will try learn better javascript. I need to pass data stored in "event" to object."event".id (to be like players.John.id instead players.event.id)
Sorry for my bad english.
// in app.js
var fs = require('fs');
var socketio = require('socket.io');
Tail = require('tail').Tail;
var express = require('express');
var http = require('http');
var colors = require('colors');
var app = express()
, server = require('http').createServer(app)
, io = socketio.listen(server); // socket needs to listen on http server
server.listen(9099);
app.use(express.static(__dirname + '/public'));
var port = process.env.PORT || 3000;
app.listen(port, function() {
console.log('\r\n');
console.log("Express listening on port " + port +'.'.green);
});
// Routing
//app.use(express.static(__dirname));
// usernames which are currently connected to the chat
//var players = [];
var players = {};
io.sockets.on('connection', function(socket) {
// do all of your socket work in here
console.log('\r\n');
console.log("Connection".green);
var sessionid = socket.id;
console.log(sessionid);
// Success! Now listen to messages to be received
socket.on('message',function(event){
console.log('Received message:',event);
});
socket.on('add user',function(event){
console.log('New User:',event);
// we store the username in the socket session for this client
socket.username = event;
// add the client's username to the global list
players.event = {};
players.event.id = sessionid;
//players.John.foo = "yeah"
//players.John.name = "John"
console.log(players);
socket.emit('login', {});
// echo globally (all clients) that a person has connected
socket.broadcast.emit('user joined', {
username: socket.username
});
});
//socket.emit('start', 'newround');
});
edit2
Got it working.
// in app.js
var fs = require('fs');
var socketio = require('socket.io');
Tail = require('tail').Tail;
var express = require('express');
var http = require('http');
var colors = require('colors');
var app = express()
, server = require('http').createServer(app)
, io = socketio.listen(server); // socket needs to listen on http server
server.listen(9099);
app.use(express.static(__dirname + '/public'));
var port = process.env.PORT || 3000;
app.listen(port, function() {
console.log('\r\n');
console.log("Express listening on port " + port +'.'.green);
});
// Routing
//app.use(express.static(__dirname));
// usernames which are currently connected to the chat
//var players = [];
var players = {};
io.sockets.on('connection', function(socket) {
// do all of your socket work in here
console.log('\r\n');
console.log("Connection".green);
var sessionid = socket.id;
console.log(sessionid);
// Success! Now listen to messages to be received
socket.on('message',function(event){
console.log('Received message:',event);
});
socket.on('add user',function(event){
console.log('New User:',event);
// we store the username in the socket session for this client
socket.username = event;
// add the client's username to the global list
players[event] = {};
players[event].id = sessionid;
//players.John.foo = "yeah"
//players.John.name = "John"
console.log(players);
socket.emit('login', {});
// echo globally (all clients) that a person has connected
socket.broadcast.emit('user joined', {
username: socket.username
});
});
//socket.emit('start', 'newround');
});
You're looking for a players object, with individual players referenced by name. So:
var players = {};
players['John'] = {
'age' = 12,
'address' = 'London...',
'telnumber' = '09876587655'
};
You can also access "John" as players.John, but that gets tricky if any of the names contain spaces, etc.
Similarly, the player attributes can be accessed either via:
players.John['age'] = 13;
or
players.John.age = 13;
var name = "John";
var players = {};
players[name] = {};
players[name].age = '12';
players[name].address = "address";
players[name].telnumber = "tel";

Categories

Resources