I am executing a code in NodeJS child_process.
I used MailParser of Andris9.
I used console.log(JSON.stringify({obj:mail_object})); to get the data of mail_object to the parent.
In the parent, I have this code, JSON.parse(retVal);.
The error came up is "Unexpected end of Input".
This error only shows when the email I received is having an attachment.
If the email doesnt have attachment, there is no error.
Here is the parent method,
getEmails(){
let workerProcess = child_process.spawn('node', [basePath+'imports/workers/retrieveEmail.js']);
workerProcess.stdout.on('data', function (data) {
try{
let retVal = new Buffer(data).toString();
retVal = JSON.parse(retVal);
console.log(retVal);
if(typeof retVal.err == "undefined"){
console.log(retVal.obj.from[0].address);
Fiber(function () {
var objs = [];
if (typeof retVal.obj.attachments !== "undefined") {
console.log("Test passed");
retVal.obj.attachments.forEach(function (attachment) {
let future = new Future();
Fiber(function () {
Files.write(attachment.content, {
fileName: attachment.fileName,
type: attachment.contentType
}, function (error, fileRef) {
if (error) {
future.throw(new Meteor.Error(500, error.message));
} else {
...
}
});
}).run();
var bool = true;
if (bool = future.wait())
objs.push(bool);
});
}
...
}).run();
}else{
console.log(retVal.err);
}
}catch(e){
console.log(e);
}
});
workerProcess.stderr.on('data', function (data) {
console.log('stderr: ' + data);
});
workerProcess.on('close', function (code) {
console.log('child process exited with code ' + code);
});
},
I removed some unnecessary codes.
Here is my retrieveEmail.js,
...
client.on("retr", function (status, msgnumber, data, rawdata) {
if (status === true) {
var mailparser = new MailParser({
streamAttachments: false
});
var timeStamp = Math.floor(Date.now());
mailparser.on("attachment", function (attachment, mail) {
console.log(JSON.stringify({err:"testpassed1"}));
});
mailparser.on("end", function (mail_object) {
console.log(JSON.stringify({err:"testpassed2"}));
console.log(JSON.stringify({obj:mail_object}));
});
mailparser.write(data);
mailparser.end();
client.dele(msgnumber);
} else {
console.log("RETR failed for msgnumber " + msgnumber);
client.quit();
}
});
...
Related
Lobbies.json
{"Lobbies":[]}
jsonWorker.js
const fs = require('fs');
function lobbyUpdater(name, password) {
let rawdata = fs.readFileSync('Lobbies.json');
let data = JSON.parse(rawdata);
// data.Lobbies.length = 0; // Remove this for production
let newLobby = {"Name":name, "Password":password, "Players":1, "Mode":"", "Word":""}
data.Lobbies.push(newLobby)
fs.writeFile('Lobbies.json', JSON.stringify(data), 'utf8', function(err) {
if (err) throw err;
});
}
function lobbyAvailable(name) {
let rawdata = fs.readFileSync('Lobbies.json');
let data = JSON.parse(rawdata);
for (let i = 0; i < data.Lobbies.length; i++) {
if (data.Lobbies[i].Name.toUpperCase() === name.toUpperCase()) {
return false;
}
}
return true;
}
module.exports = {
lobbyUpdater,
lobbyAvailable
};
post Request on index.js
app.post('/newLobby', (req, res) => {
console.log("Lobby Name:", req.body.lobbyName);
console.log("Lobby Password:", req.body.lobbyPassword);
const jsonWorker = require('./jsonWorker');
if (jsonWorker.lobbyAvailable(req.body.lobbyName)) {
jsonWorker.lobbyUpdater(req.body.lobbyName, req.body.lobbyPassword);
}
else {
res.sendStatus(403);
console.log("Stopped A Lobby From Being Created");
}
});
Code from react that is being followed
<Link id="testLink" to="/Waiting-For-Players"><button id="submit" onClick={sendingRequest} className="WaitingForPlayers">Create Lobby</button></Link>
sendingRequest function
function sendingRequest(event) {
event.preventDefault();
$.post("http://localhost:4000/newLobby",
{
lobbyName: document.getElementById('lobbyName').value,
lobbyPassword: document.getElementById('lobbyPassword').value
},
function (data, status) {
console.log("Data", data);
})
.fail(function(jqXHR, textStatus, errorThrown) {
console.log("Error received:", errorThrown);
console.log("Stopping the post request.");
return;
})
.then(function() {
// Follow the Link component
let linkToUse = document.getElementById("testLink");
window.location.assign(linkToUse.to);
console.log("Testing")
});
}
My goal is to only have the Link be stopped if the post request throws a 403 forbidden since the lobby name would have already been in the json. The link should go through otherwise. I believe that the issue is that the .then function isn't going through as the console.log isn't showing up but I am really not sure why it isn't working. Any help would be appreciated thanks!
I created a function called Sensors and instantiated the serialport object within it. I also created a prototype find that in theory should access the port object to open, write and bind on.
I'm receiving error:
Uncaught TypeError: Cannot read property 'open' of undefined
I'm not sure why....
Code:
<script>
var sp = require('serialport');
var comports = [];
//Object to connect to a specific comport and send the 'i' command
function Sensors(com) {
this.find();
this.address = com;
this.port = new sp(com, {
baudrate: 9600,
autoOpen: false
});
}
Sensors.prototype.find = function() {
console.log("ran");
this.port.open(function(err) {
if (err) {
return console.log('Error opening port: ', err.message);
}
this.port.write('i' + String.fromCharCode(13), function(err) {
if (err) {
return console.log('Error on write: ', err.message);
}
console.log('message written');
});
this.port.on('data', function(data) {
var sensorData = data;
var splitString = sensorData.toString().split(',');
console.log(splitString[1]);
if (sensorData.length > 0) {
if (splitString[1] == 'pH' || splitString[1] == 'EC' || splitString[1] == 'RTD') {
console.log(splitString[1]);
}
this.port.close(function(err) {
console.log('port closed', err);
});
}
});
});
};
function findSensors() {
sp.list(function(err, ports) {
for (i = 0; i < ports.length; i++) {
var sensor = new Sensors(ports[i].comName);
sensor.find();
}
});
}
//startup function to find comports and find the sensor(s)
function startUp() {
findSensors();
}
</script>
In the constructor, you're calling this.find(); before you've assigned to this.port, so the line this.port.open inside find results in an error. Change it so that this.find runs after the port property has been populated.
function Sensors(com) {
this.address = com;
this.port = new sp(com, {
baudrate: 9600,
autoOpen: false
});
this.find();
}
I am using a javascript bridge to communicate between a hybrid web app and iOS using a webView.
my question is how to get the function ios_getUserID() from within the script to put a value to the variable UserID that exists above the javascript bridge function.
I have a web page and connected to it is a script js file. scripts.js looks like this:
var userID="";
//javascript ios bridge
window.onerror = function(err) {
log('window.onerror: ' + err)
}
function connectWebViewJavascriptBridge(callback) {
if (window.WebViewJavascriptBridge) {
callback(WebViewJavascriptBridge)
} else {
document.addEventListener('WebViewJavascriptBridgeReady', function() {
callback(WebViewJavascriptBridge)
}, false)
}
}
connectWebViewJavascriptBridge(function(bridge) {
var uniqueId = 1
function log(message, data) {
var log = document.getElementById('log')
var el = document.createElement('div')
el.className = 'logLine'
el.innerHTML = uniqueId++ + '. ' + message + ':<br/>' + JSON.stringify(data)
if (log.children.length) { log.insertBefore(el, log.children[0]) }
else { log.appendChild(el) }
}
bridge.init(function(message, responseCallback) {
log('JS got a message', message)
var data = { 'Javascript Responds':'Weeeeeeee!' }
log('JS responding with', data)
responseCallback(data)
})
bridge.registerHandler('testJavascriptHandler', function(data, responseCallback) {
log('ObjC called testJavascriptHandler with', data)
var responseData = { 'Javascript Says':'Right back atcha!' }
log('JS responding with', responseData)
responseCallback(responseData)
})
bridge.registerHandler('softUserID', function(data, responseCallback) {
log('softUserID ObjC called testJavascriptHandler with', data)
alert(data.userID);
var responseData = { 'Javascript Says':'super!' }
log('JS responding with', responseData)
responseCallback(responseData)
})
ios_getUserID = function(){
var obj = '{"action" : "getUserID"}';
//alert("crossing bridge");
var data = obj
log('JS sending message', data)
bridge.send(data, function(responseData) {
log('JS got response', responseData)
alert(responseData);
})
}
});
In my flow say i am using an access token for getting my data. When my access token expires i get a 401 error i am using the refresh token to get a new access token.
Note : My access token and refresh token is stored in a cookie and i am updating the same after a 401 error.
My question how do i retry the same operation which i was in the middle of?
My Code (services.js):
var refresh_token = "na";
function get_api_data(url, api_token) {
var returnData = handleApiData(url, api_token, "GET");
return returnData;
}
function post_api_data(url, api_token, post_data) {
var returnData = handleApiData(url, api_token, "PUT", post_data);
return returnData;
}
function handleApiData(url, access_token, type, post_data) {
return $.ajax({
url: url,
type: type,
data: post_data,
error: failHandler,
contentType: "application/json",
beforeSend: function (xhr) {
xhr.setRequestHeader("Authorization", "Bearer " + access_token);
}
})
}
function handleData(data, textStatus, jqXHR) {
return data;
}
function failHandler(jqXHR, textStatus, errorThrown) {
switch (jqXHR.status) {
case 401:
var api = get_api_token();
checkApiToken(api.refresh_token);
break;
default:
alert(errorThrown);
}
}
function checkApiToken(refresh_token) {
if (refresh_token != "na") {
$.post("/Account/Refresh/?refresh_token=" + refresh_token);
//location.reload();
}
}
My Code (notification.js):
$(function () {
var api = get_api_token();
if (api != null)
get_notification_data(api.access_token);
});
function get_notification_data(api_token) {
var notifications = get_api_data(urls.notifications.list, api_token);
if (notifications != undefined)
notifications.success(function (data) {
items = data.records;
_.each(items, function (item) {
item.Status = ko.observable(item.status);
item.onClick = function () {
if (item.Status() === 'UNREAD') {
var post_data = { id: item.id };
post_api_data(urls.notifications.list, api_token, post_data).success(function (response, textStatus) {
if (response.success)
item.Status('READ');
$(location).attr("href", item.action_link);
});
}
else {
$(location).attr("href", item.action_link);
}
}
});
var model = {
items: ko.observableArray(items),
onCancel: function (item) {
}
}
ko.applyBindings(model, $("#notificationBar")[0]);
})
}
Edit: My AccountController code that sets the new API cookie:
[HttpPost]
public ActionResult Refresh(string refresh_token)
{
string token_string = string.Empty;
try
{
token_string = OAuthHelper.getTokenViaRefreshTokenFromAPIServer(refresh_token);
if(token_string != null)
Response.Cookies[Constants.Cookies.API].Value = token_string;
}
catch (Exception ex)
{
Log.Info(string.Format("AccountController.cs -Refresh Token Error ", ex.Message));
}
return RedirectToAction("Index","Home");
}
If a message comes in for server01, both server01 and server02's message events will be triggered. I thought the line
Socket.prototype = new events.EventEmitter;
would result in completly seperate event instances
Thanks for any help!
var events = require('events');
var uuid = require('uuid');
// Server class
function Socket (host) {
var self = this;
self.options = {
"serverHost": host,
"serverName": "server",
"clientName": uuid.v4()
};
self.socket = new require('zmq').socket('router');
self.socket.identity = self.options.clientName;
self.socket.connect('tcp://' + self.options.serverHost);
self.socket.on('message', function (sender, data) {
console.log('Sender: %s', self.options.clientName);
console.log('Data: %s', data.toString());
self.emit('message', sender, data);
});
setInterval(function () {
self.socket.send([self.options.serverName, uuid.v4()]);
}, 5000);
self.send = function (obj, callback) {
var status = true;
if(obj !== 'object') {
status = false;
} else {
self.socket.send([self.options.serverName, obj]);
}
if(callback === 'function') {
callback(status);
} else {
return status;
};
};
};
Socket.prototype = new events.EventEmitter;
// Userland
var server01 = new Socket('127.0.0.1:3000');
server01.on('message', function (sender, data) {
console.log('Server01: %s', data.toString());
});
var server02 = new Socket('127.0.0.1:3000');
server02.on('message', function (sender, data) {
console.log('Server02: %s', data.toString());
});
Here is an example of the output from this script
Sender: 14d36a66-a4e7-484a-9ce0-3f0d368a6986
Data: 03e6bb47-6af0-4700-9b95-7bbc310477f6
Server01: 03e6bb47-6af0-4700-9b95-7bbc310477f6
Server02: 03e6bb47-6af0-4700-9b95-7bbc310477f6
Sender: 59ec292e-abd2-4c9f-ac3e-2bf92c656fde
Data: d66cd320-c3f2-4842-b66b-1d89f656d32f
Server01: d66cd320-c3f2-4842-b66b-1d89f656d32f
Server02: d66cd320-c3f2-4842-b66b-1d89f656d32f
The problem is the way you manage inheritance. Correct JavaScript code for inheritance is:
Socket.prototype = Object.create(EventEmitter.prototype);