Retrive single data from json object in nodejs - json

i am new in nodejs . i tried the below code for retriving json object. but i can't retrive a single data from json object
My code is
function getData(){
var http = require('http');
var qs = require('querystring');
var str = '';
var options = {
host: '192.168.1.16',
port: 8080,
path: '/courseapi/view'
};
callback = function(response) {
response.on('data', function (chunk) {
str += chunk;
});
response.on('end', function () {
console.log(str);
console.log(str[0]._id);
});
}
var req = http.request(options, callback).end();
};
i tried this str[0]._id but it return undefined

Try:
response.on('end', function () {
str = JSON.parse(str);
console.log(str);
console.log(str[0]._id);
});

Related

Firebase Functions Multipart/formdata Error

My webpage provides functionallity to convert pdf to image.
For Webpage i am using Firebase Hosting and for functions obvs Functions.
But after file upload function logs error in firebase dashboard Boundary not found
Below is the code i used to upload file in html:
function uploadFile() {
var file = document.getElementById("file_input").files[0];
var pass = document.getElementById("pass").value;
console.log(file + pass);
var formdata = new FormData();
formdata.append("file", file);
formdata.append("password", pass);
var ajax = new XMLHttpRequest();
ajax.upload.addEventListener("progress", progressHandler, false);
ajax.addEventListener("load", completeHandler, false);
ajax.addEventListener("error", errorHandler, false);
ajax.addEventListener("abort", abortHandler, false);
ajax.open("POST", "/upload");
ajax.setRequestHeader("Content-Type", "multipart/form-data");
ajax.send(formdata);
}
and this is the code of functions:
var functions = require('firebase-functions');
var process;
var Busboy;
var path = require('path');
var os = require('os');
var fs = require('fs');
exports.upload = functions.https.onRequest((req, res) => {
const busboy = new Busboy({ headers: req.headers });
const fields = {};
const tmpdir = os.tmpdir();
const uploads = {};
const fileWrites = [];
var pass = '';
busboy.on('file', (fieldname, file, filename) => {
console.log(`Processed file ${filename}`);
const filepath = path.join(tmpdir, filename);
uploads[fieldname] = filepath;
const writeStream = fs.createWriteStream(filepath);
file.pipe(writeStream);
const promise = new Promise((resolve, reject) => {
file.on('end', () => {
writeStream.end();
});
writeStream.on('finish', resolve);
writeStream.on('error', reject);
});
fileWrites.push(promise);
});
busboy.on('field', function (fieldname, val, fieldnameTruncated, valTruncated, encoding, mimetype) {
pass = val;
});
busboy.on('finish', function () {
console.log('Done parsing form!');
console.log(pass);
console.log(uploads);
process.processCard(uploads['file'], pass, 2).then((s) => {
res.end(`
<!DOCTYPE html>
<html>
<body>
ImageConverted!!
<img src="data:image/jpeg;base64,${s}" width="90%"></img>
</body>
</html>
`);
}).catch((err) => { res.end('Error: ' + err) });
});
busboy.end(req.body);
});
What am i doing wrong ?
For multipart body it is recommended to use req.rawBody instead of req.body
https://stackoverflow.com/a/48289899/6003934

Pass a parameter from client-side to server side and get result

I knows it sounds basic but I can't seem to get it right. I'm trying to get a data from the API but it needs a parameter in order to obtain the data. How can I pass the parameter and get the result which is a JSON array
$(function() {
var proxy = 'http://192.168.1.126/lms-dev-noel/proxy.php';
var endpoint = 'account/';
var rt = 'GET';
var url = proxy+'?endpoint='+endpoint+'&rt='+rt;
var param = {
'lastsyncdate' : '2016-12-06'
};
$.get(url, function(param) {
console.log('Success');
});
});
ways to achieve this :
using jQuery.ajax() method :
var proxy = 'http://192.168.1.126/lms-dev-noel/proxy.php';
var endpoint = 'account/';
var url = proxy+'?endpoint='+endpoint+'&rt='+rt;
var method = 'GET';
var params = {
'lastsyncdate' : '2016-12-06'
};
$.ajax({
url: url,
type: method, //send it through get method
data: params,
success: function(response) {
//Do Something
},
error: function(xhr) {
//Do Something to handle error
}
});
using jQuery.get() method :
var proxy = 'http://192.168.1.126/lms-dev-noel/proxy.php';
var endpoint = 'account/';
var url = proxy+'?endpoint='+endpoint+'&rt='+rt;
var method = 'GET';
var params = {
'lastsyncdate' : '2016-12-06'
};
$.get(url, params, function(res) {
console.log(res);
});
I just pass parameters as name value pairs like so...
$.get(
"yoururl.php",
{ color: "red", size: "small" }, // your params go here as name / value pairs
function(response){
console.log(response);
}
);

nodejs puts post data into new json

When I sending post request by this code:
var data = '{data: 1111}'; // = JSON.stringify(message);
console.log('NotifySplitter: ' + data);
var options = cfg.splitterOptions;
options.headers['Content-Length'] = Buffer.byteLength(data)
var req = http.request(options, function(res) {
res.setEncoding('utf8');
res.on('data', function (chunk) {
console.log("body: " + chunk);
});
});
req.write(data);
req.end();
... and getting data by this code:
var express = require('express');
var app = express();
app.use(express.bodyParser());
app.post('/', function(request, response){
var query = request.body;
console.log(request.body);
response.end();
});
request.body contains:
{'{data: 1111}': ''}
instead expected {data: 1111}. Is it normal? How to get normal data without replacing external {} in origin data before post?
You have to set up an appropriate content-type. If you're sending json, add options.headers['Content-Type'] = 'application/json' to your request.
Also, {data: 1111} is not a JSON, it's JSON5. While it's better all around, it's not supported by default express.bodyParser(), so watch out for that.

decodeAudioData failing with null errors on continuous stream

In my following code ffmpeg is transcoding the input stream and is successfully sending the chunks to the client. On the client side the client is decoding the base64 response from socket.io and is converting the response to an array buffer. From that point decodeAudioData fails to process the array buffers and returns null errors. Does anyone know why decodeAudioData isn't working?
./webaudio_svr.js:
var express = require('/usr/local/lib/node_modules/express');
var http = require('http');
var spawn = require('child_process').spawn;
var util = require('util');
var fs = require('fs');
var app = express();
var webServer = http.createServer(app);
var audServer = http.createServer(app);
var io = require('/usr/local/lib/node_modules/socket.io').listen(webServer, {log: false, });
app.use(express.static(__dirname + '/public'));
app.get('/', function(req, res){
res.send(
"<script src='/socket.io/socket.io.js'></script>\n"+
"<script>var socket=io.connect('http://127.0.0.1:3000');</script>\n"+
"<script src='/webaudio_cli.js'></script>"
);
});
webServer.listen(3000);
var inputStream = spawn('/usr/bin/wget', ['-O','-','http://nprdmp.ic.llnwd.net/stream/nprdmp_live01_mp3']);
var ffmpeg = spawn('ffmpeg', [
'-i', 'pipe:0', // Input on stdin
'-ar', '44100', // Sampling rate
'-ac', 2, // Stereo
'-f', 'mp3',
'pipe:1' // Output on stdout
]);
io.sockets.on('connection', function(webSocket) {
var disconnect = '0';
if (disconnect == '0') {
inputStream.stdout.pipe(ffmpeg.stdin);
ffmpeg.stdout.on('data', function(data) {
var data64 = data.toString('base64');
webSocket.emit('stream',data64);
});
}
webSocket.on('disconnect', function() {
disconnect=1;
});
});
./public/webaudio_cli.js:
function str2ab(str) {
var buf = new ArrayBuffer(str.length*2); // 2 bytes for each char
var bufView = new Uint16Array(buf);
for (var i=0, strLen=str.length; i<strLen; i++) {
bufView[i] = str.charCodeAt(i);
}
return buf;
}
window.AudioContext = window.AudioContext || window.webkitAudioContext;
var context = new AudioContext();
var source = context.createBufferSource();
socket.on('stream', function(data) {
var data=str2ab(atob(data));
context.decodeAudioData(data, function(buffer) {
source.connect(context.destination);
source.buffer = buffer;
source.start(0);
}, function(err) {
console.log("err(decodeAudioData): "+err);
});
});
If you read the notes section of the original post you'll see that I ended up getting this working with binaryjs but with the help of Kevin I was able to get this to work with socket.io. Note there this is still a HUGE issue with choppy playback. If someone could lend some assistance to cleaning the audio up please do. This solution is really pointless unless the audio works as expected so I need to figure that out.
The issue has to do with how the browser encodes/decodes your base64 string. Until this is changed you must supply your own functions from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Base64_encoding_and_decoding.
webaudio_svr.js:
var express = require('/usr/local/lib/node_modules/express');
var http = require('http');
var spawn = require('child_process').spawn;
var util = require('util');
var fs = require('fs');
var app = express();
var webServer = http.createServer(app);
var io = require('/usr/local/lib/node_modules/socket.io').listen(webServer, {log: false, });
app.use(express.static(__dirname + '/public'));
app.get('/', function(req, res){
res.send(
"<script src='/socket.io/socket.io.js'></script>\n"+
"<script>var socket=io.connect('http://127.0.0.1:3000');</script>\n"+
"<script src='/base64.js'></script>\n"+
"<script src='/webaudio_cli.js'></script>"
);
});
webServer.listen(3000);
var inputStream = spawn('/usr/bin/wget', ['-O','-','http://nprdmp.ic.llnwd.net/stream/nprdmp_live01_mp3']);
var ffmpeg = spawn('ffmpeg', [
'-i', 'pipe:0', // Input on stdin
'-ar', '44100', // Sampling rate
'-ac', 2, // Stereo
'-f', 'mp3',
'pipe:1' // Output on stdout
]);
io.sockets.on('connection', function(webSocket) {
var disconnect = '0';
if (disconnect == '0') {
inputStream.stdout.pipe(ffmpeg.stdin);
ffmpeg.stdout.on('data', function(data) {
var data64 = data.toString('base64');
webSocket.emit('stream',data64);
});
}
webSocket.on('disconnect', function() {
disconnect=1;
});
});
public/webaudio_cli.js:
window.AudioContext = window.AudioContext || window.webkitAudioContext;
var context = new AudioContext();
var startTime = context.currentTime;
// buffer to arraybuffer
function toArrayBuffer(buffer) {
var ab = new ArrayBuffer(buffer.length);
var view = new Uint8Array(ab);
for (var i = 0; i < buffer.length; ++i) {
view[i] = buffer[i];
}
return ab;
}
socket.on('stream', function(data) {
var data=toArrayBuffer(base64DecToArr(data));
context.decodeAudioData(data, function(buffer) {
playBuffer(buffer);
}, function(err) {
console.log("decodeAudioData err: "+err);
});
});
function playBuffer(buf) {
var source = context.createBufferSource();
source.buffer = buf;
source.connect(context.destination);
source.start(startTime);
startTime = startTime+source.buffer.duration;
}
public/base64.js:
copy and paste functions from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Base64_encoding_and_decoding#Solution_.232_.E2.80.93_rewriting_atob()_and_btoa()_using_TypedArrays_and_UTF-8

Node Server receive XmlHttpRequest

I'm using the following code to send a session description (tiny JSON code - http://www.ietf.org/rfc/rfc2327.txt).
function sendMessage(message) {
var msgString = JSON.stringify(message);
console.log('C->S: ' + msgString);
path = '/message?r=67987409' + '&u=57188688';
var xhr = new XMLHttpRequest();
xhr.open('POST', path, true);
xhr.send(msgString);
}
I'm not sure how to go about retreiving the JSON on my Node.js server.
Here's a code that can handle POST request in node.js .
var http = require('http');
var server = http.createServer(function (request, response) {
if (request.method == 'POST') {
var body = '';
request.on('data', function (data) {
body += data;
});
request.on('end', function () {
var POST = JSON.parse(body);
// POST is the post data
});
}
});
server.listen(80);
Hope this can help you.