Chunk/Stream API data using Node.js - node.js

We have requirement where we need to write a node application which can read URL of image from database (approx more than million). Use image-size npm package to retrieve image meta data like height, width. Here should be an API which can list out result.
I am able to console log data but when i convert it to API, i need to chunk data so it can start appearing on browser and i'm unable to do that and need help. Here is my code
var express = require('express');
var url = require('url');
var http = require('http');
var sizeOf = require('image-size');
const sql = require('mssql');
var app = express();
var port = process.env.PORT || 3000;
const hostname = 'localhost';
var config1 = {
user: '*********',
password: '*********',
server: '*********',
database: '*******',
port: 1433,
debug: true,
options: {
encrypt: false // Use this if you're on Windows Azure
}
};
app.get('/', function(req, res){
//res.writeHead(200, { 'Content-Type': 'application/json' });
var finalResult = [];
sql.close();
sql.connect(config1, function (err) {
if (err) console.log(err);
const request = new sql.Request()
var myQuery = `select imagename from media`;
request.stream = true;
request.query(myQuery);
request.on('row', row => {
//console.log('Image : ' + row.ImageUrl);
if (row.ImageUrl != ''){
if (row.ImageUrl.indexOf('http') < 0)
row.ImageUrl = "http:" + row.ImageUrl;
var options = url.parse(row.ImageUrl);
http.get(options, function (response) {
if (response.statusCode == 200)
{
var chunks = [];
response.on('data', function (chunk) {
chunks.push(chunk);
}).on('end', function() {
var buffer = Buffer.concat(chunks);
//console.log(options.href);
//console.log(sizeOf(buffer).height);
var result = {};
result.MaskUrl = row.MaskUrl;
result.ImageUrl = options.href;
result.Height = sizeOf(buffer).height;
result.Width = sizeOf(buffer).width;
result.statusCode = 200;
finalResult.push(result);
//console.log(result);
console.log(finalResult);
res.write(result, function(){
res.end();
});
});
}
else
{
var result = {};
result.MaskUrl = row.MaskUrl;
result.ImageUrl = options.href;
result.Height = 0;
result.Width = 0;
result.statusCode = response.statusCode;
finalResult.push(result);
console.log(result);
res.write(result, function(){
res.end();
});
}
});
}
})
request.on('error', err => {
console.log ('Error for ' + row.ImageUrl );
})
request.on('done', err => {
console.log('Last Time' + finalResult.length);
})
// request.query(myQuery,(err,result) =>{
// console.log(result);
// });
});
console.log('Last Time' + finalResult.length);
res.send(finalResult);
});
app.listen(port, hostname, function(){
console.log('ImageSize running on PORT: ' + port);
});
I tried res.write, res.end without any success.

The probable reason for your problem is that here:
res.write(result, function(){
res.end();
});
You end and close the request just after the first image is read.
I would rewrite the code a little and use some functional framework, like scramjet, to stream the data straight from the DB. As Nicholas pointed out it's not super easy to run your code so I'm writing blindly - but if you fix any of my obvious error this should just work:
First:
npm install scramjet JSONStream node-fetch
Next, try this code:
var express = require('express');
var sizeOf = require('image-size');
const sql = require('mssql');
var app = express();
var port = process.env.PORT || 3000;
const hostname = 'localhost';
const {DataStream} = require('scramjet');
const fetch = require('node-fetch');
const JSONStream = require('JSONStream');
var config1 = {
user: '*********',
password: '*********',
server: '*********',
database: '*******',
port: 1433,
debug: true,
options: {
encrypt: false // Use this if you're on Windows Azure
}
};
app.get('/', function(req, res, next){
// you should consider not doing these two lines on each request,
// but I don't want to mess you code...
sql.close();
sql.connect(config1, function (err) {
if (err) next(err);
res.writeHead(200, { 'Content-Type': 'application/json' });
const request = new sql.Request();
var myQuery = `select imagename from media`;
request.stream = true;
request.query(myQuery);
const stream = new DataStream();
request.on('row', row => stream.write(row));
stream.filter(
row => row.ImageUrl !== ''
)
.map(
async row => {
if (row.ImageUrl.indexOf('http') !== 0) // url must start with http.
row.ImageUrl = "http:" + row.ImageUrl;
const response = await fetch(row.ImageUrl);
let size = {width:0, height:0};
if (response.status === 200) {
const buffer = await response.buffer();
size = sizeOf(buffer);
}
return {
MaskUrl: row.MaskUrl,
ImageUrl: row.ImageUrl,
Height: size.height,
Width: size.width,
statusCode: response.status
};
}
)
.pipe(
JSONStream.stringify()
).pipe(
res
);
request.on('error', () => {
res.writeHead(500, { 'Content-Type': 'application/json' });
stream.end("{error:true}");
});
request.on('done', () => stream.end());
});
});
app.listen(port, hostname, function(){
console.log('ImageSize running on PORT: ' + port);
});

Related

Heroku Nodejs Webhosting

Im trying to host a election website.
My Current Method explained:
There is server.js file with serves the public file. If its a POST request(sent by frontend.js to send data to server) edits the poll.json file based on the data sent.
I have a public file having index.html, frontend.js, poll.json where poll.json stores all the data.
My current code work all well in my localhost.
But when running it in Heroku I get a error in the POST request line saying 'POST http://localhost:53390/ net::ERR_CONNECTION_REFUSED1
*********.herokuapp.com/:1 Uncaught (in promise) TypeError: Failed to fetch'
My server.js code:
const createServer = require('http').createServer;
const express = require('express');
const app = express();
let pollData = require(__dirname+'/public/poll.json');
const fs = require('fs');
var all_usn_no=[];
const listening_port=process.env.PORT || 4000;
function get_roll_and_usn(pollData){
for(var i=0;i<=pollData.students.length-1;i++){
//all_roll_no.push(pollData.students[i][0]);
all_usn_no.push(pollData.students[i][1]);
}
}
function roll_to_row(in_usn){
get_roll_and_usn(pollData)
return all_usn_no.indexOf(in_usn);
}
function write_vote(votes){
var checking_row=roll_to_row(votes[1]);
pollData.students[checking_row]=votes;
fs.writeFile(__dirname+'/public/poll.json', JSON.stringify(pollData), (err) => {
if (err) throw err;
console.log('Data written to file');
});
}
write_vote([listening_port,0]);
app.use(express.static(__dirname+'/public'));
app.get('/', (req, res) => {
res.sendFile(__dirname);// + '/index.html');
});
app.post('/', (req, res) => {
let body = '';
req.on('data', data => body += data)
req.on('end', () => {
res.writeHead(200, {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'POST, GET',
});
body=body.split(",");
console.log(body.toString());
write_vote(body);
res.end(`{ "response": "${body ? body : 'No body sent' }" }`);
})
});
app.listen(listening_port, () => {
console.log('Example app listening at http://localhost:'+listening_port)
});
my frontend.js program:
var roll='';
var client_ip='';
var usn='';
var date='';
const all_roll_no=[]
const all_usn_no=[]
var port='';
function check(roll,usn){
var data='';
const url='poll.json';
const Http = new XMLHttpRequest();
Http.open("GET", url);
Http.send();
Http.onload = () =>{
data=JSON.parse(Http.response);
get_roll_and_usn(data);
check_validity(roll,usn,data);
}
}
function get_roll_and_usn(pollData){
for(var i=0;i<=pollData.students.length-1;i++){
//all_roll_no.push(pollData.students[i][0]);
all_usn_no.push(pollData.students[i][1]);
}
}
function usn_to_row(in_usn){
return all_usn_no.indexOf(in_usn);
}
function check_validity(checking_roll,checking_usn,data){
var checking_row=usn_to_row(checking_usn);
port=data.students[0][0];
//if(all_roll_no.indexOf(checking_roll)>=0 && checking_usn==all_usn_no[all_roll_no.indexOf(checking_roll)] && data.students[checking_row][2]==0){
if(all_usn_no.indexOf(checking_usn)>=0 && data.students[checking_row][2]==0){
//console.log("valid");
document.getElementById("page_2").style.display = "none";
document.getElementById("page_3").style.display = "block";
fetch('https://api.ipify.org/?format=json').then(results=> results.json()).then(data => client_ip=data.ip);
}
else{
alert("You cannot vote/ You have already voted")
//console.log('invalid');
}
}
document.getElementById("startbutton").onclick = function(){
roll = document.getElementById("roll_no").value;
usn = document.getElementById("usn_no").value;
date = Date();
check(roll,usn);
}
document.getElementById("next").onclick = function() {
document.getElementById("page_1").style.display = "none";
document.getElementById("page_2").style.display = "block";
}
document.getElementById("finish").onclick = function() {
var splb=[document.getElementById("splb1").checked,document.getElementById("splb2").checked,document.getElementById("splb3").checked,document.getElementById("splb4").checked,document.getElementById("splb5").checked,document.getElementById("splb6").checked,document.getElementById("splb7").checked];
var splg=[document.getElementById("splg1").checked,document.getElementById("splg2").checked,document.getElementById("splg3").checked,document.getElementById("splg4").checked,document.getElementById("splg5").checked,document.getElementById("splg6").checked,document.getElementById("splg7").checked];
var asplb=[document.getElementById("asplb1").checked,document.getElementById("asplb2").checked,document.getElementById("asplb3").checked,document.getElementById("asplb4").checked,document.getElementById("asplb5").checked,document.getElementById("asplb6").checked,document.getElementById("asplb7").checked];
var asplg=[document.getElementById("asplg1").checked,document.getElementById("asplg2").checked,document.getElementById("asplg3").checked,document.getElementById("asplg4").checked,document.getElementById("asplg5").checked,document.getElementById("asplg6").checked,document.getElementById("asplg7").checked];
var csb=[document.getElementById("csb1").checked,document.getElementById("csb2").checked,document.getElementById("csb3").checked,document.getElementById("csb4").checked,document.getElementById("csb5").checked,document.getElementById("csb6").checked,document.getElementById("csb7").checked];
var csg=[document.getElementById("csg1").checked,document.getElementById("csg2").checked,document.getElementById("csg3").checked,document.getElementById("csg4").checked,document.getElementById("csg5").checked,document.getElementById("csg6").checked,document.getElementById("csg7").checked];
var acsb=[document.getElementById("acsb1").checked,document.getElementById("acsb2").checked,document.getElementById("acsb3").checked,document.getElementById("acsb4").checked,document.getElementById("acsb5").checked,document.getElementById("acsb6").checked,document.getElementById("acsb7").checked];
var acsg=[document.getElementById("acsg1").checked,document.getElementById("acsg2").checked,document.getElementById("acsg3").checked,document.getElementById("acsg4").checked,document.getElementById("acsg5").checked,document.getElementById("acsg6").checked,document.getElementById("acsg7").checked];
var scb=[document.getElementById("scb1").checked,document.getElementById("scb2").checked,document.getElementById("scb3").checked,document.getElementById("scb4").checked,document.getElementById("scb5").checked,document.getElementById("scb6").checked,document.getElementById("scb7").checked];
var scg=[document.getElementById("scg1").checked,document.getElementById("scg2").checked,document.getElementById("scg3").checked,document.getElementById("scg4").checked,document.getElementById("scg5").checked,document.getElementById("scg6").checked,document.getElementById("scg7").checked];
var ascb=[document.getElementById("ascb1").checked,document.getElementById("ascb2").checked,document.getElementById("ascb3").checked,document.getElementById("ascb4").checked,document.getElementById("ascb5").checked,document.getElementById("ascb6").checked,document.getElementById("ascb7").checked];
var ascg=[document.getElementById("ascg1").checked,document.getElementById("ascg2").checked,document.getElementById("ascg3").checked,document.getElementById("ascg4").checked,document.getElementById("ascg5").checked,document.getElementById("ascg6").checked,document.getElementById("ascg7").checked];
var vote=[String(splb.indexOf(true)),String(splg.indexOf(true)),String(asplb.indexOf(true)),String(asplg.indexOf(true)),String(csb.indexOf(true)),String(csg.indexOf(true)),String(acsb.indexOf(true)),String(acsg.indexOf(true)),String(scb.indexOf(true)),String(scg.indexOf(true)),String(ascb.indexOf(true)),String(ascg.indexOf(true))]
var update=[String(roll),String(usn),"1",String(client_ip),String(date)].concat(vote);
if (update.indexOf("-1")<0){
alert("Pls vote for all posts")
}
else{
document.getElementById("page_1").style.display = "none";
document.getElementById("page_2").style.display = "none";
document.getElementById("page_3").style.display = "none";
fetch('http://localhost:'+port,{method:'POST',body:update}).then(results=> results.json()).then(console.log);
//console.log(update);
alert("Your vote has been registered")
}
}
You can just ignore the function as they are just to process the data and do necessary funtions.
Main problem: PORT request from frontend.js to server.js sending data to edit the poll.json file return error.
Thanks in advance.
Try using const PORT = process.env.PORT || 3333;
with
app.listen(PORT, () => {
console.log(`Server is starting on ${PORT}`);
})

how to create an http reverse proxy and transform the stream with node js

I have this working reverse http proxy, but when I add a transform stream and try to pipe it between, nothing seems to be streamed in any direction.
Here's the code:
const http = require('http')
const {Transform} = require('stream')
const onRequest = (clientRequest, clientResponse) => {
const options = {
hostname: 'test-host',
port: 80,
path: clientRequest.url,
method: clientRequest.method,
headers: clientRequest.headers
}
const proxy = http.request(options, (serverResponse) => {
serverResponse.pipe(myTransform, {end: true})
myTransform.pipe(clientResponse, {end: true})
})
clientRequest.pipe(myTransform, {end: true})
myTransform.pipe(proxy, {end: true})
}
const myTransform = new Transform({
transform(data, encoding, callback) {
console.log(data)
callback(null, data)
}
})
http.createServer(onRequest).listen(5050)
Here's a reduced version of a toy proxy I wrote.
It is able to work with body parser (this version is JSON-only) and transform both the request and the response.
The downside is that it's not very efficient for large requests or responses, because it reads the entire bodies of both the request and response before re-streaming them.
const express = require('express');
const bodyParser = require('body-parser');
const proxy = require('http-proxy-middleware');
const httpStatus = require('http-status-codes');
const app = express();
app.use(bodyParser.json());
app.use(function (req, res, next) {
console.log("this is where you transform the request");
});
function restreamReq(proxyReq, req, res) {
if (!req.body) {
return;
}
const contentType = req.get('content-type');
if (contentType) {
proxyReq.setHeader('content-type', contentType);
}
const contentLength = req.get('content-length');
if (contentLength) {
const bodyData = JSON.stringify(req.body);
const bufferLength = Buffer.byteLength(bodyData);
if (bufferLength != contentLength) {
console.warn(`buffer length = ${bufferLength}, content length = ${contentLength}`);
proxyReq.setHeader('content-length', bufferLength);
}
proxyReq.write(bodyData);
}
}
function restreamRes(proxyRes, req, res) {
res.status(proxyRes.statusCode);
for (const key of Object.keys(proxyRes.headers)) {
let rawValue = proxyRes.headers[key];
if (!Array.isArray(rawValue)) {
rawValue = [ rawValue ];
}
for (const value of rawValue) {
res.set(key, value);
}
}
console.log("this is where you transform the response");
let body = new Buffer('');
const bodyPromise = new Promise(function(resolve, reject) {
proxyRes.on('data', (data) => body = Buffer.concat([body, data]));
proxyRes.on('end', () => resolve());
proxyRes.on('error', (err) => reject(err));
});
bodyPromise
.then(() => res.end(body))
.catch(err => res.status(httpStatus.INTERNAL_SERVER_ERROR).end());
}
app.use(proxy({
target: 'http://localhost:8080',
changeOrigin: true,
xfwd: false,
preserveHeaderKeyCase: true,
selfHandleResponse: true,
onProxyReq: restreamReq,
onProxyRes: restreamRes,
}));
const server = app.listen(process.env.PORT || 8081);
process.on('SIGINT', function() {
server.close();
process.exit();
});

Send message synchronously with Nodejs Websocket

My app has three modules:
WebSocket Module: resides on the remote server (internet) and it acts as a Websocket
server that entertain the connection between Client Module and
Webhook module.
Webhook Module: resides on the remote server (internet) and it acts as
a webhook to answer the HTTP post request from the user. It is connected to Websocket Module via websocket as well.
Client Module: resides on my local machine and it is connected to
the
Webhook model via websocket. This client responsible to get query
from my local backend.
When a user call Webhook Module through HTTP Post request, Webhook module initiate a connection to WebSocket module via websocket. Then, the WebSocket module initiate the connection to Client module and response back with the necessary information. Actually I have to do this to eliminate the HTTP tunnel that is blocked in my company.
The problem is, when I open two browser windows to perform the HTTP Post request at the same time with different parameter, for example, param "A", I would expect to get return "A", with param "B", I expect to get "B" not "A". But There is something wrong with my codes/design. If I executed at the same time, I throw "A" then I got "B" which is wrong. How do I overcome this.
This is a simple diagram to illustrate it.
WebSocket Module:
'use strict'
//This is WebSocket Server
const clients = {};
const SocketIO = require('socket.io');
const express = require('express');
const http = require('http');
const app = express();
const server = http.createServer(app);
const ws = SocketIO(server);
const port = 3000;
var clientid;
ws.on('connection', (client) => {
clients[client.id] = client;
console.log('new connection', client.id);
clientid = client.id;
client.emit('message', { message: 'welc' })
client.on('disconnect', () => {
delete clients[client.id];
console.log('Client ' + client.id + ' disconnected. Deleted');
});
client.on('WH', function (from, msg) {
console.log('Message from Webhook', from, ' : ', msg);
client.broadcast.emit('message', { message: msg });
//console.log('send to: ' + clientid);
//ws.to(clientid).emit('hey', { message: msg });
//client.emit('message', { message: msg })
});
client.on('CL', function (from, msg) {
console.log('Message from Client', from, ' : ', msg);
client.broadcast.emit('message', 'me', msg);
//ws.to(client.id).emit('message', 'me', msg);
//client.emit('message', 'me', msg);
});
});
server.listen(process.env.PORT || port);
console.log('WebSocket Server is running on port ' + port);
Webhook Module
'use strict'
//This is WebHook Server
const express = require('express');
const bodyParser = require('body-parser');
const request = require('request');
const http = require('http');
const io = require('socket.io-client');
const app = express()
app.use(bodyParser.json())
const clients = {};
const SocketIO = require('socket.io');
const server = http.createServer(app);
const ws = SocketIO(server);
const port = 5000;
let Res;
let httpreq = false;
let nctid;
let ts;
const socket = io.connect('http://localhost:3000', {reconnect: true});
// Add a connect listener
socket.on('connect', function() {
console.log('Connected to WebSocket server!');
});
socket.on('message', function(from, msg) {
//console.log('Message from ', from, ' : ', msg);
console.log('nctid: ' + nctid + ', ts: ' + ts);
//Get the message from Client
if (httpreq) {
Res.send({
replies: [{
type: 'text',
content: msg,
}],
conversation: {
memory: {
key: msg
}
}
})
httpreq = false;
}
});
app.listen(process.env.PORT || port, () => {
console.log('Webhook server is running on port ' + port);
})
app.post('/', (req, res) => {
//console.log(req.body)
let query = req.body.nlp.entities.query[0].value;
nctid = req.body.nlp.entities.nctid[0].value;
ts = Math.floor(Date.now() / 1000);
console.log("query: " + query + '|' + nctid + '|' + ts);
//Send message to WebSocket server with parameter query and NCTID
socket.emit('WH', 'me', query + '|' + nctid);
Res = res;
httpreq = true;
})
app.post('/errors', (req, res) => {
console.log(req.body);
res.send();
})
Client Module
'use strict'
//This is client app running on client premise
const request = require('request');
const parser = require('xml2json');
const io = require('socket.io-client');
const socket = io.connect('http://localhost:3000', {reconnect: true});
// Add a connect listener
socket.on('connect', function(socket) {
console.log('Connected to WebSocket server!');
});
socket.on('message', function(from, msg) {
//console.log('MSG', from, ' : ', msg);
console.log(from);
let param = from.message.split('|');
let query = param[0];
let nctid = param[1];
if (typeof nctid != 'undefined') {
getNCTID(nctid, function(returnValue) {
//console.log(returnValue);
try {
let json = parser.toJson(returnValue);
json = JSON.parse(json);
if (query == 'title')
socket.emit('CL', 'me', 'Title is ' + json.clinical_study.brief_title);
else
socket.emit('CL', 'me', 'Status is ' + json.clinical_study.overall_status);
} catch (e) {
console.log(e);
socket.emit('CL', 'me', 'No NCTID ' + nctid);
}
});
}
});
function getNCTID(nctid, callback) {
let url = "https://clinicaltrials.gov/ct2/show/" + nctid + "?displayxml=true";
let options = {
url: url,
method: 'GET'
}
//console.log(options);
let requestWithEncoding = function(options, callback) {
let req = request.get(options);
req.on('response', function(res) {
let chunks = [];
res.on('data', function(chunk) {
chunks.push(chunk);
});
res.on('end', function() {
let buffer = Buffer.concat(chunks);
let encoding = res.headers['content-encoding'];
if (encoding == 'gzip') {
zlib.gunzip(buffer, function(err, decoded) {
callback(err, decoded && decoded.toString());
});
} else if (encoding == 'deflate') {
zlib.inflate(buffer, function(err, decoded) {
callback(err, decoded && decoded.toString());
})
} else {
callback(null, buffer.toString());
}
});
});
req.on('error', function(err) {
callback(err);
});
}
requestWithEncoding(options, function(err, data) {
if (err) {
console.log('err:' + err);
callback('error');
} else
//console.log(data);
callback(data);
})
}

Node.js, Proxy HTTPS traffic without re-signing

I'm building a proxy using Node.js to be run on my local machine that will log all domains accessed. Kind of the same way Fiddler works, but my program is more simple, I don't need to look at the data or decrypt anything.
I got this working fine for HTTP but for HTTPS it resigns the traffic with the self-signed certificate provided. This results in that the browser displays a warning. The same thing doesn't happen in fiddler unless you choose to decrypt HTTPS traffic.
So my question is: How do I proxy HTTPS traffic using Node.js so that it is completely transparent for the user?
This is the code I'm using right now, using the Node.js http-proxy. Based on the Github project, proxy-mirror.
var httpProxy = require('http-proxy'),
https = require('https'),
connect = require('connect'),
logger = connect.logger('dev'),
EventEmitter = require('events').EventEmitter,
util = require('util'),
Iconv = require('iconv').Iconv,
convertBuffer = require('./convertBuffer'),
fs = require('fs'),
net = require('net'),
url = require('url'),
path = require('path'),
certDir = path.join(__dirname, '/../cert'),
httpsOpts = {
key: fs.readFileSync(path.join(certDir, 'proxy-mirror.key'), 'utf8'),
cert: fs.readFileSync(path.join(certDir, 'proxy-mirror.crt'), 'utf8')
};
var Session = function (sessionId, req, res) {
EventEmitter.call(this);
var that = this;
this.id = req._uniqueSessionId = res._uniqueSessionId = sessionId;
this.request = req;
this.request.body = {asString: null, asBase64: null};
this.response = res;
this.response.body = {asString: null, asBase64: null};
this.state = 'start';
var hookInResponseWrite = function () {
var response = that.response;
var _write = response.write;
var output = [];
response.write = function (chunk, encoding) {
output.push(chunk);
_write.apply(response, arguments);
};
return output;
}, hookInRequestData = function () {
var request = that.request,
output = [];
request.on('data', function (chunk, encoding) {
output.push(chunk);
});
request.on('end', function () {
var buffersConcatenated = Buffer.concat(output);
request.body.asString = buffersConcatenated.toString();
that.emit('request.end', that);
});
return output;
};
this.response.bodyBuffers = hookInResponseWrite();
this.request.bodyBuffers = hookInRequestData();
this.ended = function () {
var buffersConcatenated = Buffer.concat(this.response.bodyBuffers);
this.response.body.asString = convertBuffer.convertEncodingContentType(buffersConcatenated,this.response.getHeader('content-type') || '');
this.response.body.asBase64 = buffersConcatenated.toString('base64');
this.removeAllListeners();
};
};
util.inherits(Session, EventEmitter);
Session.extractSessionId = function (req) {
return req._uniqueSessionId;
};
var SessionStorage = function () {
var sessionHash = {},
sessionIdCounter = 0,
nextId = function () {
return sessionIdCounter += 1;
};
this.startSession = function (req, res) {
var sessionId = nextId(), session;
sessionHash[sessionId] = session = new Session(sessionId, req, res);
return session;
};
this.popSession = function (req) {
var sessionId = Session.extractSessionId(req),
session = sessionHash[sessionId];
delete sessionHash[sessionId];
return session;
};
};
var ProxyServer = function ProxyServer() {
EventEmitter.call(this);
var proxyPort = 8888,
secureServerPort = 8887,
parseHostHeader = function (headersHost, defaultPort) {
var hostAndPort = headersHost.split(':'),
targetHost = hostAndPort[0],
targetPort = parseInt(hostAndPort[1]) || defaultPort;
return {hostname: targetHost, port: targetPort, host: headersHost};
},
sessionStorage = new SessionStorage(),
adjustRequestUrl = function(req){
if (requestToProxyMirrorWebApp(req)) {
req.url = req.url.replace(/http:\/\/localhost:8889\//, '/');
}
req.url = url.parse(req.url).path;
},
proxyServer = httpProxy.createServer({
changeOrigin: true,
enable: {
xforward: false
}
}, function (req, res, proxy) {
var parsedHostHeader = parseHostHeader(req.headers['host'], 80),
targetHost = parsedHostHeader.hostname,
targetPort = parsedHostHeader.port;
req.originalUrl = req.url;
adjustRequestUrl(req);
logger(req, res, function () {
proxy.proxyRequest(req, res, {
host: targetHost,
port: targetPort
});
})
}),
proxy = proxyServer.proxy,
secureServer = https.createServer(httpsOpts, function (req, res) {
var parsedHostHeader = parseHostHeader(req.headers.host, 443);
// console.log('secure handler ', req.headers);
req.originalUrl = req.url;
if(!req.originalUrl.match(/https/)){
req.originalUrl = 'https://' + parsedHostHeader.host + req.url;
}
adjustRequestUrl(req);
logger(req, res, function () {
proxy.proxyRequest(req, res, {
host: parsedHostHeader.hostname,
port: parsedHostHeader.port,
changeOrigin: true,
target: {
https: true
}
});
});
}),
listening = false,
requestToProxyMirrorWebApp = function (req) {
var matcher = /(proxy-mirror:8889)|(proxy-mirror:35729)/;
return req.url.match(matcher) || (req.originalUrl && req.originalUrl.match(matcher));
};
[secureServer,proxyServer].forEach(function(server){
server.on('upgrade', function (req, socket, head) {
// console.log('upgrade', req.url);
proxy.proxyWebSocketRequest(req, socket, head);
});
});
proxyServer.addListener('connect', function (request, socketRequest, bodyhead) {
//TODO: trying fixing web socket connections to proxy - other web socket connections won't work :(
// console.log('conenct', request.method, request.url, bodyhead);
var targetPort = secureServerPort,
parsedHostHeader = parseHostHeader(request.headers.host);
if(requestToProxyMirrorWebApp(request)){
targetPort = parsedHostHeader.port;
}
var srvSocket = net.connect(targetPort, 'localhost', function () {
socketRequest.write('HTTP/1.1 200 Connection Established\r\n\r\n');
srvSocket.write(bodyhead);
srvSocket.pipe(socketRequest);
socketRequest.pipe(srvSocket);
});
});
this.emitSessionRequestEnd = function (session) {
this.emit('session.request.end', session);
};
this.startSession = function (req, res) {
if (requestToProxyMirrorWebApp(req)) {
return;
}
var session = sessionStorage.startSession(req, res);
this.emit('session.request.start', session);
session.on('request.end', this.emitSessionRequestEnd.bind(this));
};
this.endSession = function (req, res) {
if (requestToProxyMirrorWebApp(req)) {
return;
}
var session = sessionStorage.popSession(req);
if (session) {
session.ended();
this.emit('session.response.end', session);
}
};
this.start = function (done) {
done = done || function () {
};
proxy.on('start', this.startSession.bind(this));
proxy.on('end', this.endSession.bind(this));
proxyServer.listen(proxyPort, function () {
secureServer.listen(secureServerPort, function () {
listening = true;
done();
});
});
};
this.stop = function (done) {
done = done || function () {
};
proxy.removeAllListeners('start');
proxy.removeAllListeners('end');
if (listening) {
secureServer.close(function () {
proxyServer.close(function () {
listening = false;
done();
});
});
}
};
};
util.inherits(ProxyServer, EventEmitter);
module.exports = ProxyServer;

Get my twitter timeline instead of public twitter timeline using Node JS

This code works fine but it seems that it retrieve any tweet not only the people I follow, I want to get my timeline tweets
what should I do ?
var open = require('open');
var sys = require('sys');
var spawn = require('child_process').spawn
var OAuth= require('oauth').OAuth;
var express = require("express");
var util = require('./util');
var app = express();
var oa = new OAuth(
"https://api.twitter.com/oauth/request_token",
"https://api.twitter.com/oauth/access_token",
"NeFpQZNDapDtFJnUXDe0Q",
"mXf7AKYJWIdiToKuSgsTm2me0GBA1aNn39uskmEoOM",
"1.0",
"http://127.0.0.1:8080/twitterCallback",
"HMAC-SHA1"
);
var oauthtoken ,oauthtokensecret;
{
oa.getOAuthRequestToken(function(error, oauth_token, oauth_token_secret, results){
if (error) {
console.log(error);
res.send("yeah no. didn't work.")
}
else {
oauthtoken = oauth_token;
oauthtokensecret = oauth_token_secret;
open('http://twitter.com/oauth/authenticate?oauth_token='+oauthtoken);
}
});
}
var http = require('http');
var fs = require('fs');
function readFile(fileName,response){
fs.readFile(fileName, function (err,data) {
if (err) {
return console.log(err);
}
response.end(data);
});
}
var server = http.createServer(function(req, res) {
if(req.url == '/favicon.ico'){
res.end('Hello Http');
}else if(req.url.indexOf('twitterCallback') != -1){
res.writeHead(200);
res.end('Hello Http');
var url = require('url');
var url_parts = url.parse(req.url, true);
var query = url_parts.query;
var oauth_verifier = query.oauth_verifier;
console.log(oauth_verifier);
oa.getOAuthAccessToken(oauthtoken,oauthtokensecret,query.oauth_verifier, function(error, oauth_access_token, oauth_access_token_secret, results)
{
if (error){
console.log(error);
} else {
//console.log("oauth_access_token = " + oauth_access_token);
//console.log("oauth_access_token_secret = " + oauth_access_token_secret);
}
var twitter = require('ntwitter');
var twit = new twitter({
consumer_key: 'NeFpQZNDapDtFJnUXDe0Q',
consumer_secret: 'mXf7AKYJWIdiToKuSgsTm2me0GBA1aNn39uskmEoOM',
access_token_key: oauth_access_token,
access_token_secret: oauth_access_token_secret
});
twit.stream('statuses/sample', function(stream) {
stream.on('data', function (data) {
console.log(data.text);
});
});
}
);
}else{
readFile(req.url.substr(1));
}
});
server.listen(8080);
Use the ntwitter library : https://github.com/AvianFlu/ntwitter
And to consume api :
var twitter = require('ntwitter');
var twit = new twitter({
consumer_key: 'Twitter',
consumer_secret: 'API',
access_token_key: 'keys',
access_token_secret: 'go here'
});
twit.stream('user', {track:'nodejs'}, function(stream) {
stream.on('data', function (data) {
console.log(data);
});
stream.on('end', function (response) {
// Handle a disconnection
});
stream.on('destroy', function (response) {
// Handle a 'silent' disconnection from Twitter, no end/error event fired
});
// Disconnect stream after five seconds
setTimeout(stream.destroy, 5000);
});

Resources