The subject content is undefined - javascript

I have a small problem using mailparser. When I'm trying to see the subject content it says that is undefined.
My code looks something like this :
var fs = require("fs");
var socket = fs.createWriteStream('./outputmail.eml');
socket.on("end",function()
{
connection.loginfo("end------->");
});
connection.transaction.message_stream.pipe(socket, {}); // haraka related
var mailparser = new MailParser();
mailparser.on("end", function(mail_object){
connection.loginfo("----------SUBJECT-------------------->:", mail_object.subject);
});
fs.createReadStream("./outputmail.eml").pipe(mailparser);
I'm using mailparser in Haraka (http://haraka.github.io) . The whole point doing this, is that I want to parse every mail I receive and add a banner/image/whatever into the mail's body. If you have any idea why this message appears , please let me know.

If that is the code it is likely that you start reading the file before it is written. As the libraries both support streams you should be able to pipe the message_stream directly to mailparser, ie.
var mailparser = new MailParser();
mailparser.on("end", function(mail_object) {
console.log(mail_object);
});
connection.transaction.message_stream.pipe(mailparser, {});
Another reason could naturally be that there just isn't a subject in the email.

Related

Is it possible to write text in the middle of a file with fs.createWriteStream ? (or in nodejs in general)

I'm trying to write in a text file, but not at the end like appendFile() do or by replacing the entiere content...
I saw it was possible to chose where you want to start with start parameter of fs.createwritestream() -> https://nodejs.org/api/fs.html#fs_fs_createwritestream_path_options
But there is no parameter to say where to stop writting, right ? So it remove all the end of my file after I wrote with this function.
const fs = require('fs');
var logger = fs.createWriteStream('result.csv', {
flags: 'r+',
start: 20 //start to write at the 20th caracter
})
logger.write('5258,525,98951,0,1\n') //example a new line to write
Is there a way to specify where to stop writting in the file to have something like:
....
data from begining
....
5258,525,98951,0,1
...
data till the end
...
I suspect you mean, "Is it possible to insert in the middle of the file." The answer to that is: No, it isn't.
Instead, to insert, you have to:
Determine how big what you're inserting is
Copy the data at your insertion point to that many bytes later in the file
Write your data
Obviously when doing #2 you need to be sure that you're not overwriting data you haven't copied yet (either by reading it all into memory first or by working in blocks, from the end of the file toward the insertion point).
(I've never looked for one, but there may be an npm module out there that does this for you...)
You could read/parse your file at first. Then apply the modifications and save the new file.
Something like:
const fs = require("fs");
const fileData = fs.readFileSync("result.csv", { encoding: "utf8" });
const fileDataArray = fileData.split("\n");
const newData = "5258,525,98951,0,1";
const index = 2; // after each row to insert your data
fileDataArray.splice(index, 0, newData); // insert data into the array
const newFileData = fileDataArray.join("\n"); // create the new file
fs.writeFileSync("result.csv", newFileData, { encoding: "utf8" }); // save it

updating a file that is being used in a variable

I'm using a variable to store a json file that is used as a reference in my code. i have a code that checks if the variable is outdated or not. if it is outdated, it will be updated from its source.
const someFile = require('./something.json')
Everytime the file was outdated, the program tries to update it. and it was successful. however, nodejs kept using the old .json file (that has been replaced) as a reference. making my code output an outdated response.
so how can I tell node.js to use the updated file? thank you in advance!
//myjson.json
{
"data": {
"name": "uday",
"age": 25
}
}
controller.js
var myJSON = require('./myjson.json');
var fs = require('fs');
console.log("before change-->", myJSON);
myJSON.data.age = 26;
console.log("after change-->", myJSON);
fs.writeFileSync('myjson.json', JSON.stringify(myJSON));
console result
before change--> { data: { name: 'uday', age: 25 } }
after change--> { data: { name: 'uday', age: 26 } }
Your issue is with the const keyword, when a value gets assigned to a constant it cannot be changed (Info), just use let keyword and your code should work.
Update
If both files exist :
let someFile= require('./ab.json')
console.log(someFile); // Will Print content of ab.json
someFile= require('./bc')
console.log(someFile); // Will Print content of bc.json
But this would only work for already existing files on app start. So for a run time created file you cannot use require for that you need another option like the fs module (Docs Node 8.x)
P.S : While it's valid solution, if the file is a json and gets changed regularly you can just use redis and it's Keyspace Notifications if this is a large scale application if not fs is the way to go.
As described in Require Documentation, require will cache the file, so even if you update the file and use require again to get the file you wont see the changes.
Caching
Modules are cached after the first time they are loaded. This means
(among other things) that every call to require('foo') will get
exactly the same object returned, if it would resolve to the same
file.
Instead can try reading the file each time.
var fs = require('fs');
var data = fs.readFileSync('something.json', 'utf8');
var someFile = JSON.parse(data);

at WebSocket.socket.onerror in LiveQueryClient.js when start app

I have a problem with my small demo for live query as in attached image.
To be honest, I have no idea why does it go wrong. Try to find some solutions around but not yet successfully. Please give me some ideas or solutions if you know this issue. Thanks so much.
Parse server example: 1.4.0
Parse JS SDK: 1.10.2
NodeJS: 8.9.1
npm: 5.5.1
P/S: I have added classes for supporting by Live Query already.
Here is the source which run successfully without using Live Query
Link to src with removed parse link:
var Parse = require('parse/node');
Parse.initialize("shetei5aeJ9Aequi6deejojiv7foh6Hieg2eesh9keingohw");
Parse.serverURL = 'serURLhere';
var Node = Parse.Object.extend('Node');
var q = new Parse.Query('Node');
var subscription = q.subscribe();
var procEventOpen = () => {
console.log('subscription opened...');
};
subscription.on('open', procEventOpen);
This happened to me when I had a typo in server url.
Try to explicit specify liveQueryServerURL parameter:
Parse.liveQueryServerURL = 'ws://yourserverurl/parse';
Note the ws instead of http(s)

Load webpage in NodeJs

I'm just wondering how I can load a webpage within nodejs, I've been searching for 2 days and I can't find anything. Either I'm using the wrong search terms or I'm just not looking for what I actually need.
I need to open a link to authenticate an account and I've retrieved the URL that I need to open but I'm not sure how. I've tried http.request but it mustn't be loading the page as when I check if the account has been verified it hasn't.
How would I go about this?
Thanks (Sorry for nooby question and bad formatting)
Buck
P.S Oops I wrote it in such a hurry I forgot to add the snippet of my code
var http = require('http');
var options = {
host: Host, //Both variables defined earlier in the code this is just a snippet of the http.request part
path: Path
};
callback = function(response) {
var string = '';
response.on('data', function (blob) {
string += blob;
});
response.on('end', function () {
console.log(string);
});
}
http.request(options, callback).end();
It just returns
['R޾�\s۝�V������T��:�I����$��v�* �*�;�* P���q�ܠ���5�E!9��I���v��r��� �CmO����q��<�>���&�趩�C��i�&��a��q�(��1a4I^XvLe�T˔�|��M�3�EA!نY\0�h�R��#r�b�a��Yr��z��1аB
Even when I try
console.log(string.toString('utf8'));
I managed to find what the problem was and fix it,
Further above in my code I had not declared an important variable properly.
http.request works perfectly

Create exportable object or module to wrap third-party library with CommonJS/NodeJS javascript

I'm new to JavaScript and creating classes/objects. I'm trying to wrap an open source library's code with some simple methods for me to use in my routes.
I have the below code that is straight from the source (sjwalter's Github repo; thanks Stephen for the library!).
I'm trying to export a file/module to my main app/server.js file with something like this:
var twilio = require('nameOfMyTwilioLibraryModule');
or whatever it is I need to do.
I'm looking to create methods like twilio.send(number, message)that I can easily use in my routes to keep my code modular. I've tried a handful of different ways but couldn't get anything to work. This might not be a great question because you need to know how the library works (and Twilio too). The var phone = client.getPhoneNumber(creds.outgoing); line makes sure that my outgoing number is a registered/paid for number.
Here's the full example that I'm trying to wrap with my own methods:
var TwilioClient = require('twilio').Client,
Twiml = require('twilio').Twiml,
creds = require('./twilio_creds').Credentials,
client = new TwilioClient(creds.sid, creds.authToken, creds.hostname),
// Our numbers list. Add more numbers here and they'll get the message
numbers = ['+numbersToSendTo'],
message = '',
numSent = 0;
var phone = client.getPhoneNumber(creds.outgoing);
phone.setup(function() {
for(var i = 0; i < numbers.length; i++) {
phone.sendSms(numbers[i], message, null, function(sms) {
sms.on('processed', function(reqParams, response) {
console.log('Message processed, request params follow');
console.log(reqParams);
numSent += 1;
if(numSent == numToSend) {
process.exit(0);
}
});
});
}
});`
Simply add the function(s) you wish to expose as properties on the exports object. Assuming your file was named mytwilio.js and stored under app/ and looks like,
app/mytwilio.js
var twilio = require('twilio');
var TwilioClient = twilio.Client;
var Twiml = twilio.Twiml;
var creds = require('./twilio_creds').Credentials;
var client = new TwilioClient(creds.sid, creds.authToken, creds.hostname);
// keeps track of whether the phone object
// has been populated or not.
var initialized = false;
var phone = client.getPhoneNumber(creds.outgoing);
phone.setup(function() {
// phone object has been populated
initialized = true;
});
exports.send = function(number, message, callback) {
// ignore request and throw if not initialized
if (!initialized) {
throw new Error("Patience! We are init'ing");
}
// otherwise process request and send SMS
phone.sendSms(number, message, null, function(sms) {
sms.on('processed', callback);
});
};
This file is mostly identical to what you already have with one crucial difference. It remembers whether the phone object has been initialized or not. If it hasn't been initialized, it simply throws an error if send is called. Otherwise it proceeds with sending the SMS. You could get fancier and create a queue that stores all messages to be sent until the object is initialized, and then sends em' all out later.
This is just a lazy approach to get you started. To use the function(s) exported by the above wrapper, simply include it the other js file(s). The send function captures everything it needs (initialized and phone variables) in a closure, so you don't have to worry about exporting every single dependency. Here's an example of a file that makes use of the above.
app/mytwilio-test.js
var twilio = require("./mytwilio");
twilio.send("+123456789", "Hello there!", function(reqParams, response) {
// do something absolutely crazy with the arguments
});
If you don't like to include with the full/relative path of mytwilio.js, then add it to the paths list. Read up more about the module system, and how module resolution works in Node.JS.

Categories

Resources