Rectangle 27 31

var mailer = require("nodemailer");

// Use Smtp Protocol to send Email
var smtpTransport = mailer.createTransport("SMTP",{
    service: "Gmail",
    auth: {
        user: "gmail_id@gmail.com",
        pass: "gmail_password"
    }
});

var mail = {
    from: "Yashwant Chavan <from@gmail.com>",
    to: "to@gmail.com",
    subject: "Send Email Using Node.js",
    text: "Node.js New world for me",
    html: "<b>Node.js New world for me</b>"
}

smtpTransport.sendMail(mail, function(error, response){
    if(error){
        console.log(error);
    }else{
        console.log("Message sent: " + response.message);
    }

    smtpTransport.close();
});

I found Nodemailer way easier to use than node-email-templates. Maybe it's because I was just trying to send basic plaintext/basic html email, but I found node-email-templates needed way more setting up, whereas Nodemailer was up and running in literally 2 minutes.

Other than gmail ? How can we configure for our own smtp server ?

Sending emails in Node.js? - Stack Overflow

node.js email-integration
Rectangle 27 9

The simplest way I found to just send raw XML to a SOAP service using Node.js is to use the Node.js http implementation. It looks like this.

var http = require('http');
var http_options = {
  hostname: 'localhost',
  port: 80,
  path: '/LocationOfSOAPServer/',
  method: 'POST',
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded',
    'Content-Length': xml.length
  }
}

var req = http.request(http_options, (res) => {
  console.log(`STATUS: ${res.statusCode}`);
  console.log(`HEADERS: ${JSON.stringify(res.headers)}`);
  res.setEncoding('utf8');
  res.on('data', (chunk) => {
    console.log(`BODY: ${chunk}`);
  });

  res.on('end', () => {
    console.log('No more data in response.')
  })
});

req.on('error', (e) => {
  console.log(`problem with request: ${e.message}`);
});

// write data to request body
req.write(xml); // xml would have been set somewhere to a complete xml document in the form of a string
req.end();

You would have defined the xml variable as the raw xml in the form of a string.

But if you just want to interact with a SOAP service via Node.js and make regular SOAP calls, as opposed to sending raw xml, use one of the Node.js libraries. I like node-soap.

@Abhisheksaini the above example is a post.

Node.js: how to consume SOAP XML web service - Stack Overflow

xml node.js soap
Rectangle 27 51

You should be able to use mustache.js, if it doesn't work send me the issues and I'll get it fixed because I'm about to be using them in node.js anyway.

I know that it works without a DOM because a bunch of CouchDB standalone apps are using it in a Spidermonkey view server.

There is also a blog post about using Mustache and Underscore together with Node.js: boldr.net/create-a-web-app-with-node

javascript - Is there a template engine for Node.js? - Stack Overflow

javascript template-engine node.js
Rectangle 27 3

The best way to send messages from server to client right now is using webSockets. The basic concept is this:

  • Client A runs some javascript that creates a webSocket connection to server B.
  • Server B accepts that webSocket connection and the socket stays open for the duration of the life of the web page.
  • Server B registers event handlers to handle incoming messages from the web page.
  • Client A registers event handlers to handle incoming messages from the server.
  • At any point in time, the server can proactively send data to the client page and it will receive that data.
  • At any point in time, the client may sent data to the server and it will receive that data.

A popular node.js library that makes webSocket support pretty easy is socket.io. It has both client and server support so you can use the same library for both ends of the connection. The socket.io library supports the .emit() method mentioned in your question for sending a message over an active webSocket connection.

You don't directly call functions from client to server. Instead, you send a message that triggers the server to run some particular code or vice versa. This is cooperative programming where the remote end has to be coded to support what you're asking it to do so you can send it a message and some optional data to go with the message and then it can receive that message and data and execute some code with that.

So, suppose you wanted the server to tell the client anytime a temperature changed so that the client could display in their web page the updated temperature (I actually have a Raspberry Pi node.js server that does exactly this). In this case, the client web page establishes a webSocket connection to the server when the page loads. Meanwhile, the server has its own process that is monitoring temperature changes. When it sees that the temperature has changed some meaningful amount, it sends a temperature change message to each connected client with the new temperature data. The client receives that message and data and then uses that to update it's UI to show the new temperature value.

The transaction could go the other way too. The client could have a matrix of information that it wants the server to carry out some complicated calculation on. It would send a message to the server with the type of calculation indicated in the message type and then send the matrix as the data for the message. The server would receive that message, see that this is a request to do a particular type of calculation on some data, it would then call the appropriate server-side function and pass it the client data. When the result was finished on the server, it would send a message back to the client with the result. The client would receive that result and then do whatever it needed to with the calculated result.

Note, if the transactions are only from client to server with a response then coming back from the server, a webSocket is not needed for that type of transaction. That can be done with just an Ajax call. Client makes ajax call to the server, server formulates a response and returns the response. Where webSockets are most uniquely useful is if you want to initiate the communication from the server and send unsolicited data to the client at a time that the server decides. For that, you need some continuous connection between client and server which is what a webSocket is designed to be.

It appears there may be more to your question about how to communicate from a C# server to your node.js server so it can then notify the client. If this is the case, then since the node.js server is already a web server, I'd just add a route to the node.js server so you can simply do an http request from the C# server to the node.js server to pass some data to the node.js server which it can then use to notify the appropriate client via the above-described webSocket connection. Depending upon your security needs, you may want to implement some level of security so that the http request can only be sent locally from your C# server, not from the outside world to your node.js server.

This cooperation between client and server is what I'm after. My application is simply a program written in c# that spawns a process that runs the node server. The client essentially controls a moving object in the C# application, when this object reaches some location marker, I want the c# application to tell the server to emit a message. This is why I am after a solution that allows me to emit messages after the server has started. This would be easily done by calling a JavaScript function through HTML on the client webpage but how can this be achieved on the Server

@Marcus - a challenge with this question is that you never really described the whole problem. Are you asking how a C# application can notify the node.js application to send a webSocket message to the client? Is that the question? Because I've fully described how the node.js server would send a message to the client already. So, is the remaining part of the question how the C# application would communicate with an already runniong node.js server to tell it to notify the client? If so, then I'd suggest a simple Ajax call (e.g. http request) from C# to the node.js server.

I agree. As I have already successfully implemented the client and can call JavaScript functions to send messages to the Server I posed my question with this in mind, which is why I asked for a way to trigger a function call after the Server had started. I felt the c# part was not necessary to add as I could've implemented that if the triggering a function call was possible, I see the confusion and I acknowledge your description of inter message transmission. I will look into the Ajax calling you described.

javascript - Send message from Node.js Server to Client via function c...

javascript node.js socket.io
Rectangle 27 14

A bit late, but you could communicate with your node client using the Redis Pub/Sub mechanism in a very simple and effective way. All you need to do is install redis on your server.

On the php side, initialize Redis then publish a message

$purchase_info = json_encode(array('user_id' =>$user_id,
         'purchase_information'=>array('item'=>'book','price'=>'2$'));

$this->redis->publish('transaction_completed', $purchase_info);
var redis = require('redis');
var purchase_listener = redis.createClient();
purchase_listener.subscribe('transaction_completed');
purchase_listener.on('message', function(channel, message){
    var purchase_data = JSON.parse(message);
    user_id = purchase_data.user_id;
    purchase_info = purchase_data.purchase_information;
    // Process the data
    // And send confirmation to your client via a socket connection
})

When talking about scalability you need to think about your infrastructure's architecture and your particular needs but here's a quick answer : I've been using a variant of this mechanism on a high traffic real-time application without problems but here's what you should be careful about:

The nice thing about this system is that you don't need to add anything to your existing infrastructure and can get started immediately, it's very fast and it behaves exactly like an HTTP server.

  • Using a self-hosted fast messaging queue server (ActiveMQ, RabbitMQ, beanstalkd ... ) server to handle your messaging logic between php and node, these tend to be fast but as the load increases you lose a bit of performance, and have to maintain/scale your messaging servers, and take care of duplication across regions which is not an easy and enjoyable thing (depending on what you enjoy doing).
  • Using a hosted messaging queue server (IronMQ, SQS...) Some of these(IronMQ) are pretty fast and will be great for your use case but introduce some (minor) complexity to your codebase.
  • Using HTTP inside a VPN to communicate with node servers. Once you see your traffic spiking you will only need to load-balance your node servers and add as much stateless servers as you need and send POST messages to that load balancer.

The point of this lengthy edit is that there is no such thing as a magic scalable solution, you need to weigh your options and see which one works the best for your use case. In my opinion, if you're starting to build your first iteration now, choose any option that you're comfortable with, write very clean code and when you start scaling it will be very easy to change, this is what I've done :)

Thanks, very useful

What about high traffic application. Is this mechanism salable ? I would like to use redis and laravel for my real time application. Please let me know if its successful.

Sending messages from PHP to Node.js - Stack Overflow

php node.js
Rectangle 27 1

It does not matter the total clock time that it takes to get data from an external service as long as you are using asynchronous requests. What matters is how much CPU you are using in doing so. If the majority of the time is waiting for the external service to respond or to send the data, then your node.js server is just sitting idle most of the time and you probably do not need a child process.

Because node.js is asynchronous, it can happily have many open requests that are "in flight" that it is waiting for responses to and that takes very little system resources.

Because node.js is single threaded, it is CPU usage that typically drives the need for a child process. If it takes 5 minutes to get a response from an external service, but only 50ms of actual CPU time to process that request and do something with it, then you probably don't need a child process.

If it were me, I would separate out the code for communicating with the external service into a module of its own, but I would not add the complexity of a child process until you actually have some data that such a change is needed.

I don't really know if there is a big cost to start a new child process every 5 minutes or if I should use only one long time running child process or if I am overthinking the problem

There is definitely some cost to starting up a new child process. It's not huge, but if you're going to be doing it every 5 minutes and it doesn't take a huge amount of memory, then it's probably better to just start up the child process once, have it manage the scheduling of communicating with the external service entirely upon it's own and then it can communicate back results to your other node.js process as needed. This makes the 2nd node process much more self-contained and the only point of interaction between the two processes is to communicate an update. This separation of function and responsibility is generally considered a good thing. In a multi-developer project, you could more easily have different developers working on each app.

ok nice explanation, so if I don't have some blocking task, I should not worry about that before problem(= performance issue) happens ?

@Thomas - Yep, that would be my advice. Don't complicate things until you have actual evidence that it is needed.

node.js - NodeJs App - Repeated job - Single or multiple child process...

node.js child-process
Rectangle 27 2

In the other app (client)

What you're looking for is called an RPC server. It allows external clients to execute exposed functions in your app. Luckily python has many RPC options. ZeroRPC is probably my favorite as it is easy to use and supports node.js. Here is an example of how to expose your send method using ZeroRPC:

import zerorpc

class HelloRPC(object):
    def send(self, message):
        url = ("https://testserver.com/socket?message=%s") % (message)
        req = urllib2.Request(url, None, None)
        response = urllib2.urlopen(req).read()
        return response    
s = zerorpc.Server(HelloRPC())
s.bind("tcp://0.0.0.0:4242")
s.run()
import zerorpc

c = zerorpc.Client()
c.connect("tcp://127.0.0.1:4242")
print c.send("RPC TEST!")

@MethodMan - what OS are you running?

Hi, Running windows. I finally managed to fix it with a pre-compiled version but now im experiencing an "LostRemote: Lost remote after 10s heartbeat" exception. Not sure if I put the call in the wrong place. Im testing now :) Thanks for your help. Ill let you know if I get it working.

It uses tcp so make sure your firewall isn't blocking. Set a break point at def send and see if it is hitting the method. You can use a command line client on the same box to test.

If their examples work then your send method is probably throwing an error. Wrap in a try except and return a message to confirm

Calling methods from an already running python script - Stack Overflow

python python-2.7 python-3.x gevent greenlets
Rectangle 27 0

Use child_process.fork if you want to create a unique Node.js process for each queue. Using fork you can send JSON messages back and forth between the Node processes.

If the process you want to create is a non Node.js process then use the child_process.exec method. Exec takes a string representing a standard terminal command.

Hmm.. basically what's happening right now is that my SQS queues are filling up and aren't "draining" at a decent rate, so I was playing with the idea of multi-threading the SQS queue draining process, but just not sure how to do it

child process - Not understanding child_process/forking in Node.js - S...

node.js child-process
Rectangle 27 0

Batch.com provides a simpler API named Transactional API to send a notification to one or more users identified by their User ID, Firebase UID etc. as you probably don't want to deal with the complexity of APNS push tokens or GCM registration ids yourself. Contrary to FCM, you will get a complete analytics view (eg: open-rate) on those notifications.

You can trigger push notifications directly from your app code by using our Swift client for the Transactional API or by coding your own HTTP client (it's a standard POST request with a JSON body). We even have a client for Node.js if you decide to trigger the notifications from a server.

And if you are using Firebase, we have a specific documentation to plug Firebase with Batch.

android - Push Notification to Specific Logged In User using Firebase/...

android firebase push-notification firebase-cloud-messaging firebase-notifications
Rectangle 27 0

An effective way to send data between native apps and a server is using a REST server. REST is based on HTTP requests and allows you to modify data on the server, which can connect to your database. The data returned is typically either JSON or XML formatted. See here for a brief intro: http://www.infoq.com/articles/rest-introduction

Android/iOS/etc have built in APIs for making HTTP requests. Your native app would send a request to the server, parse the response, and update your native UI accordingly. The same server can be used from a website using jQuery ajax HTTP requests.

Express.js is more suited to serving web pages and includes things like templating. Look into "restify" (see here: mcavage.me/node-restify/) if you just want to have a REST server that handles requests. Both run on top of node.js (nodejs.org).

As far as real-time communication, if you're developing for iOS look into APNS (Apple Push Notification Service). Apple maintains a persistent connection, and by going through their servers you can easily send messages to your app. The equivalent of this on Android is GCM (Google Cloud Messaging).

You can also do sockets directly if that's easier for you. Be careful with maintaining an open socket on a mobile device though, it can be a huge battery drain. Here's a library for connecting ObjC to Socket.IO using websockets, it may be useful for you: https://github.com/pkyeck/socket.IO-objc

All you've done is tell me what each technology is responsible for in the development cycle, which if I'm already working them, I know exactly what they do...

javascript - Express web sockets and a central server - Stack Overflow

javascript node.js sockets express socket.io