How does Node.JS work as opposed to PHP? - javascript

I'm thinking of switching from PHP to using Node.js for developing my website. However, after researching Node.js for a little while, I can't seem to find exactly how to write a webpage with Node. I see that you use response.write() in Node to write html to your webpage, but that seems like a tedious thing to do, having your entire webpage as a string literal in your node file. How does web development work in Node as opposed to PHP's method of embedding the script into the HTML file?

You don't necessarily need to use response.write for each line of the view, you can use template engines as well. Search for "node.js template engines". At first impression it could seem tedious, but a similar approach prevents you from writing bad code.

PHP is a scripting language, node is a platform built on javascript.
To start web development using node.js, at first you have to understand what makes node different. Node gives you a way to make async calls to your database (which is a very simplified explanation), which you can then wrap in nice html and send (route) it to the browser. Alternatively, you can use something like angular.js in the frontend and use node.js to make db requests and response which is picked up by angular.js which updates the front html. If you like the idea of Single page app with async calls to fetch data, use node with angular. The tutorial that I like is https://scotch.io/tutorials/creating-a-single-page-todo-app-with-node-and-angular Hope this helps!

As others have answered, there exist templating engines for Node. With the current trends in web development, most modern web frameworks encourage the separation of code from the view (or the HTML you deliver to the client). For instance, Ruby's ERB templates, Jinja2 in Python, Handlebars/Jade for Node, and now a lot of modern PHP frameworks support this as well (Zend/Slim).
Another main difference is in how they work and how the languages are designed. PHP is an object oriented language supporting classes, inheritance, member visibility, interfaces, etc. Node.js is Javascript, so using prototypical inheritance.
The communities and ecosystems are different as well. Modern PHP tends to embrace the use of the Composer package manager, and that came after PEAR. However, npm is the official node package manager and it is deeply integrated with the platform. It is trivial to search for new packages and then use them in your projects.
The main architectural difference is that Node is also asynchronous by design, meaning it runs in a single thread and can potentially handle much more connections than PHP on systems with limited memory. When a request comes in to a PHP application, all the services/controllers and everything you defined have to be reinstatiated, you define PHP files and let Apache/Nginx process them. In Node you have a node process which you can proxy outside requests to.

Node.js Provides so many modules to do these things there is framework called express for node.js http://expressjs.com/ You can use a templating engine and create views. some examples are like ejs or jade. It doesnt have to be a string.

PHP is very strongly orientated towards creating web pages from a template, while Node.js is lower-level and broader in scope. A very rough overview of the differences between PHP and Node.js:
In PHP, you'd start a web server (almost certainly Apache), and then put a PHP file in a directory where you want to serve something from. You might use some fancy .htaccess directives to make URLs nicer, etc.
In Node.js you create a script, in which you use the http module to start a web server, and then you supply a callback for whenever a request is made to your server. Deciding which page to respond to the request with, etc, is all your work to do.
In PHP, things like routing a request to a particular PHP file, compression, decoding POST and GET variables, are all done by using Apache - your PHP files are sort of just like templates which Apache runs whenever a request is received. In Node.js, everything, from starting the server to sending HTML, is all done within your Node.js script - you have to do everything.
HTML isn't the first class citizen in Node.js that it is PHP. Generally, in Node.js you are just sending strings to the client. There are plenty of third party templating tools for Node.js - but they will be dependencies, not builtin functions.

Related

Can I use JavaScript instead of PHP, replacing Apache with Node.js?

Can I write my web-site only in JavaScript being sure that my code is concealed from anyone? In this respect, is Node.js, like Apache, can be given access to through an Internet-provider?
The answer to both of your questions is yes.
Node.js can completely replace Apache (assuming you are willing to re-write all of your PHP as JavaScript). If you have your Apache running in reverse-proxy mode between your server and client, you can even handle some requests in Node.JS while handing others in PHP. This will allow you to maintain original functionality while changing the code out, and also allow PHP to handle more mundane tasks.
While you cannot prevent raw JavaScript from being read through any means of obfuscation, you can prevent people from reading your code by note making use of standard JavaScript at all. You can use a NativeExtension for Node to add an extension handler for encrypted JavaScript files:
require.extensions[".jse"] = function (m) {
m.exports = MyNativeExtension.decrypt(fs.readFileSync(m.filename));
};
require("YourCode.jse");
This will convert your JavaScript code to a .jse, which you would then package for production. Considering the encryption is done inside the native extension, the encryption key wouldn't be revealed.
Hope this helps! :)
Yes, you definitely can. It may, however, take a while to transition existing code, and if this is for a corporate institution, you'll have to ask your coworkers and your boss/supervisor. Good luck, and remember, always document your code in JavaScript (no types) all languages.
NodeJS is much faster: http://www.hostingadvice.com/blog/comparing-node-js-vs-php-performance/
Many more libraries: http://npmjs.org
Only need one language for everything
Comparing PHP with another technology like Node.js which is meant for an entirely different type of task, comparer must mention the difference of use-case/context in which one is suitable over others.
Let's talk about in terms of a different area of execution because we can not Disgrace any of them and both have its own priority.
If you talk about in terms of Application Domain.
PHP :
CMS (Content Management Systems) like WordPress, Drupal also use PHP which makes it possible to be used in creating blogs, websites, e-commerce sites, etc.
Used in developing CPU-intensive applications like meteorology applications and scientific applications.
should be used in applications in which the client does not have to interact with the server again and again
PHP 7 is based on the PHPNG engine that speeds up PHP applications more than the previous PHP interpreter (Zend Engine 2.0). Thanks to PHPNG, your apps see up to the 2x faster performance and 50% better memory consumption than PHP 5.6.
NodeJs:
Nodejs is ideal for developing highly scalable server-side solutions because of its non-blocking I/O, and event-driven model.
Used massively in Real-time applications like chat applications, blogs, video streaming applications.
Used in developing single-page applications like resume portfolios, individual websites.
Node.js should be used for the applications which require a lot of interaction between client and server.
For some tasks, Node.js may be faster than the “standard” web server with PHP because it runs as a single thread with non-blocking IO for each connection, hence there is no memory overrun. Due to this, Node.js is useful when there is a need to process data in real-time (chats, games, video, big data streams without logic)
PHP is Still alive and he has learned its lessons from Node.JS
ReactPHP enables developers to write PHP-based socket server to process requests constantly as well as Node.js does it (yes, Node.js is faster, but the fact is that PHP can also do it). The same thing with Workers (the classes responsible for running asynchronous jobs and synchronizing their results) or Amp (libraries that are used for writing non-blocking asynchronous code). Hence, it is easy to create long-running processes using PHP. Additionally, there are a lot of tools for supporting and managing these processes (such as supervisord).
So, the same tasks may be performed either with PHP or with Node.js. The question “what tool to use” is a question of personal preferences. you can use Node.js for tasks involving big data flows and PHP for tasks involving complex logic, high-load tasks, for dealing with external utilities, applications, and OS.
From the scalability perspective, there are no big differences between PHP and Node.js, it is more important to consider the project’s architecture.
Dayle Rees (a Laravel Framework contributor and developer): For a long time PHP was the butt of many language jokes, but I honestly feel that it’s becoming not only a popular language but a powerful one. PHP7 is great. The speed boost is one thing, but having optional support for full type hinting is a game changer. We’ve also got modern tools like Laravel and Composer, breathing new life into the language and its supporting community. With this in mind, I think it’s unlikely that Laravel will move from PHP. I think it’s more likely to gain further integration with front-end tools to provide a complete application building platform. That’s where I see it heading in terms of future expansion. I’m sure the Node will continue to excel when dealing with microservices and threaded applications.
The most important and most awaited News from PHP is, PHP is scheduled to receive a Just In Time (JIT) compiler in its next major version PHP-8 (most probably in sep-2021).This is going to boom the php and it breaks all his limitation due to JIT.
Wrap up
To wrap up Both have some pros, both have some cons but the amazing thing is both are created by intellects to make the web development better. While selecting the technology the question shouldn’t be which one is better but which one can serve your project needs in a better way. Understanding your project and business logic can give you a clear idea about selecting the right technology for your project.Moreover, one more important thing to consider is the skills and proficiency of the developers using the technology, how they use them and apply to the project.

Absolute simplest server-side Javascript mechanism?

I've got a simple Javascript application with a JSON API. Currently it runs in the client, but I'd like to move it from the client to the server. I am accustomed to learning new platforms, but in this case, my time is very limited - so I need to find the absolute simplest way possible.
This should be an easy task, but all I'm finding are solutions that are way overcomplicated:
The application is currently hosted on an extremely basic server. Node.js is not available, and I do not have install privileges. I'll eventually move it to a different server, but I really don't know what will be available there.
Many solutions require installing and running a standalone server. Really? Just to evaluate Javascript server-side and spit out some data?
I can run Python and PHP, and I see that it's possible to call Javascript from inside a Python or PHP script. However, the specific Python solution that I've found also require installing some Python support via pip or easy-install, so probably not an option. Also, this just feels overcomplicated, and I'm concerned about setting myself up for errors such as data conversion or permissions, etc.
Any help?
#Quentin is correct. There is no way to run javascript on a server without a javascript interpreter on the server.
Node.js is not only the most robust and widely used one, it's also the simplest. It is certainly possible to write your own javascript interpreter in PHP or Python, but that would be much more complicated than using Node.js.
Try really hard to find a server solution that allows you to use Node. In the end, it's going to save you (and any other stakeholders interested in the project) a lot of time and money.

Browser-based app needing IO control

This is a question about the best way to structure an app that has both server-side and client-side needs. Forgive the length -- I am trying to be as clear as possible with my vague question.
For a standalone non-web-connected art project, I'm creating a simple browser-based app. It could best be compared to a showy semi-complicated calculator.
I want the app to take advantage of the browser presentation abilities and run in a single non-reloading page. While I have lots of experience writing server-side apps in perl, PHP, and Python, I am newer to client-side programming, and neophyte at JavaScript.
The app will be doing a fair bit of math, a fair bit of I/O control on the Raspberry Pi, and lots of display control.
My original thought (and comfort zone) was to write it in Python with some JS hooks, but I might need to rethink that. I'd prefer to separate the logic layer from the presentation layer, but given the whole thing happens on a single non reloading html page, it seems like JavaScript is my most reasonable choice.
I'll be running this on a Raspberry Pi and I need to access the GPIO ports for both input and output. I understand that JavaScript will not be able to do I/O directly, and so I need to turn to something that will be doing AJAX-ish type calls to receive and sent IO, something like nodejs or socket.io.
My principle question is this -- Is there a clear best practice in choosing between these two approaches:
Writing the main logic of the app in client-side JavaScript and using server-side scripting to do I/O, or
Writing the logic of the app in a server-side language such as Python with calls to client-side Javascript to manage the presentation layer?
Both approaches require an intermediary between the client-side and server-side scripting. What would be the simplest platform or library to do this that will serve without being either total overkill or totally overwhelming for a learner?
I have never developed for the Raspberry Pi or had to access GPIO ports. But I have developed stand-alone web apps that acted like showy semi-complicated calculators.
One rather direct approach for your consideration:
Create the app as a single page HTML5 stand-alone web app that uses AJAX to access the GPIO ports via Node.JS or Python. Some thoughts on this approach based on my experience:
jQuery is a wonderful tool for keeping DOM access and manipulation readable and manageable. It streamlines JavaScript for working with the HTML page elements.
Keep your state in the browser local storage - using JavaScript objects and JSON makes this process amazingly simple and powerful. (One line of code can write your whole global state object to the local storage as a JSON string.) Always transfer any persistent application state changes from local variables to local storage - and have a page init routine that pulls the local storage into local variables upon any browser refresh or system reboot. Test by constantly refreshing your app as part of your testing as you develop to make sure state is managed the way you desire. This trick will keep things stable as you progress.
Using AJAX via jQuery for any I/O is very readable and reliable. It's asynchronous approach also keeps the app responsive as you perform any I/O. Error trapping and time-out handling is also easily accomplished.
For a back end, if the platform supports it, do consider Node.JS. It looks like there is at least one module for your specific I/O needs: https://github.com/EnotionZ/GpiO
I have found node to be very well supported and very easy to get started with. Also, it will keep you using JavaScript on both the front and back ends. Where this becomes most powerful is when you rely on JavaScript object literals and JSON - the two become almost interchangeable and allow you to pass complicated data structures to/from the back end via a few (or even one!) single object variable.
You can also keep your options open now on where you want to execute your math functions - since you can execute the exact same JavaScript functions in the browser or in the node back end.
If you do go the route of JavaScript and an HTML5 approach - do invest time in using the browser "developer tools" that offer very powerful debugging tools and dashboards to see exactly what is going on. You can even browse all the local storage key/value pairs with ease. It's quite a nice development platform.
After some consideration, I see the following options for your situation:
Disable browser security and directly communicate with GPIO. No standard libaries?
Use a JavaScript server environment with GPIO access and AJAX. Complexity introduced by AJAX
Use the familiar Python and use an embedded web browser If libraries are around, easy
Don't add too much complexity if you're not familiar with the tooling and language
Oh what a nice question! I'm thinking of it right now. My approach is a little difference:
With old MVC fashion, you consider the V(iew) layer is the rendered HTML page with Javascript CSS and many other things, and M and C will run on the server. And one day, I met Mr.AngularJS, I realized: Wow, some basic things may change:
AngularJS considers the View ( or the thing I believed is view ) is not actually view. AngularJS gave me Controllers, Data resources and even View templates in that "View", in another word: Client side itself can be a real Application. So now my approach is:
Server do the "server job" like: read and write data , sends data to the client, receive data from client ect....
And client do the "client job": interact with user, do the logic processes of data BEFORE IT WAS SENT such as validation, or format the information collected from user ect...
Maybe you can re-think of your approach: Ask your self what logic should run at client, what should at server. Client with javascript do its I/O, Server with server-side script do its I/O. The server will provide the needed resource for client and javascript use that resources as M(odel) of it's MVC. Hope you understand, my bad English :D
Well... it sounds like you've mostly settled on:
Python Server. (Python must manage the GPIO.)
HTML/JavaScript client, to create a beautiful UI. (HTML must present the UI.)
That seems great!
You're just wondering how much work to do on each side of the client/server divide... should be functionally equivalent.
In short: Do most of the work in whichever language you are more productive in.
Other notes come to mind:
Writing the entire server as standalone python is pretty
straightforwad.
You don't have to , but it's nice and
self-contained if you serve the page content itself from it.
If you
keep most of the state on the server/python side, you can make the
whole app a little more robust against page reloads (even though I
know you mentioned, that should never happen).

Injecting Node.js into static HTML

I'm currently looking for a way to make node.js-API-calls from static html. I've looked at Express and similar template engines, however they would require me to write my html and generate it from their template engines instead of the other way around. I often get production ready HTML from designers and don't want to rewrite that to fit with express. Alternatively is there a converter from existing .html to template engines?
To get a bit more basic, I want to use node.js in a similar way to ajax, basically being able to call things like <img onClick="someNodeFunctionWithDatabaseCalls()"> from an html-file running on node as a server and then manipulate the .html-file with DOM or something like that. Is there a way to do that?
Node.js is for server-side scripting only. In order to run node.js code in response to an event on your webpage, you will have to use websockets to send a request to your server, which can in turn run the necessary code (db requests, etc.).
As far as various web sockets go, I would recommend using socket.io; it is very simple to use, and is well known for working on many different devices. See socket.io for more information and examples.

Totally JavaScript Web Stack - Middleware, Webserver, DB suggestions?

I'm currently looking for a new web stack to build a hobby project on and would like it to be powered by JavaScript. I've had a quick look at Nitro, NarwhalJS etc. but was wondering if anyone had any solid recommendations or experience of an entire end-to-end javascript/json architecture ( jquery, middleware, standard libraries, db etc.) that they could share.
I'd prefer it to be a stack that you think is going to grow and is actively being looked after, documentation, community of nice like-minded individuals etc.
Thanks in advance.
Caveat: This answer somewhat fails to meet your basic requirement of personal experience with the resources listed. :-)
Off-the-cuff, there's Jaxer from Aptana and Chrome Server (which, despite the name, isn't related to Google Chrome AFAIK). Speaking of Chrome, though, there's an Apache CGI module that supports server-side scripting using JavaScript via Google's V8 engine, but that doesn't help you much with DB connectivity and such.
I'll also plug Java and Rhino, which I have used a bit. Via Rhino, you can compile JavaScript into Java bytecode (which, if you're using the Sun runtime, is JIT-compiled to machine code by Hotspot). That means you can run JavaScript in any servlet container (Tomcat, Resin, etc.). The joy here is that all of the huge array of goodies available for Java is instantly available to you via JavaScript -- so, MySQL connectors, image manipulation libraries, just about anything you can imagine. It's also amazingly easy to access those resources from JavaScript via Rhino. To give you an idea:
importPackage(java.io);
var f = new FileWriter("test.txt");
f.write("Testing 1 2 3");
f.close();
...and we've just written a file on the server via JavaScript, using Java's java.io.FileWriter class. You can also execute dynamic scripts at runtime via the javax.script package, which (for JavaScript) uses Rhino under the covers, although I'm not immediately coming up with a use case for doing that. :-)
For the database part of the stack:
Couchdb uses JSON and REST to store data in a document format. It uses PUT,DELETE for storage - I'm not sure how that would work with Javascript.
Helma should work well as a web server layer. It streamlines the use of Rhino as the web tier logic language.
I'm building a new service called PageForest that helps developers write totally client-side javascript programs, with PageForest providing storage and user management. Here's a sample page:
http://pfsamples.googlecode.com/svn/trunk/SAMTable/index.html#mckoss_16
This is still a work in progress, but I'd love to get some feedback on the approach. You can find more samples at the pfsamples.googlecode.com site.
Check out JScript / Windows Scripting Host(wsh) and possibly HTA's. HTA's can actually be served via a webserver and act as a locally running application with extended rights. If you want pure web development you can use WSH and some IIS tweaking to process server requests on the back end with pure javascript code in a WSF file. WSH also provides access to the file system, ODBC compliant databases and a slew of other COM exposed applications via the ActiveX model. We're not talking blazing speed, but you're programming in javascript to begin with.
Here are some links on the "stack"
http://msdn.microsoft.com/en-us/library/ms536496(VS.85).aspx
http://msdn.microsoft.com/en-us/library/15x4407c(VS.85).aspx
How about using
GWT-Spring-Hibernate-MYSql

Categories