multi threading node js code example
Example 1: how to make use of nodejs single thread to read files and attach data
var mailer = require('nodemailer');
mailer.SMTP = {
host: 'host.com',
port:587,
use_authentication: true,
user: '[email protected]',
pass: 'xxxxxx'
};
Then read a file and send an email :
fs.readFile("./attachment.txt", function (err, data) {
mailer.send_mail({
sender: '[email protected]',
to: '[email protected]',
subject: 'Attachment!',
body: 'mail content...',
attachments: [{'filename': 'attachment.txt', 'content': data}]
}), function(err, success) {
if (err) {
}
}
});
Example 2: how many threads does node js use
Example 2: Partitioned average, each of the n asynchronous steps costs O(1).
function asyncAvg(n, avgCB) {
var sum = 0;
function help(i, cb) {
sum += i;
if (i == n) {
cb(sum);
return;
}
setImmediate(help.bind(null, i+1, cb));
}
help(1, function(sum){
var avg = sum/n;
avgCB(avg);
});
}
asyncAvg(n, function(avg){
console.log('avg of 1-n: ' + avg);
});
You can apply this principle to array iterations and so forth.