Meteor - Node.js for the humanities


On a habr several times already mentioned the project Meteor , founded in 2011 by seven web technology enthusiasts from San Francisco. In fact, Meteor is just an add-on for node.js, which itself has not even reached the release version. Nevertheless, the project gathered more than seven thousand subscribers on github and received 11 million dollars of investment.
Why so popular? The point is the authors' statement that they want to radically rethink the way of writing modern web-applications in the direction of simplifying it. It's no secret that writing code on pure node.js turns the brain quite a bit and forces you to use various crutchesimagein the form of control flow of funds. On Meteor, the authors say, even the humanities can write cool applications.
Well, let's check. There is: 1 humanities sociologist, who closed the session and wants to switch to something easier after Parsons and Simmel, a computer with Ubuntu 12.10 and installed node.js (do not ask how he turned out to be a sociologist).

We will be inspired by the promises of the developers, a beautiful girl-member of the team and let's begin.


Installation is elementary - we write in the terminal
$ curl | sh

Create and run the first application

In order to create the first application, write in the terminal
$ meteor create <имя_приложения>

To start, you must write the word meteor in the application directory
$ cd <имя_приложения>
$ meteor

We go to http: // localhost: 3000 / and we see our Hello world
Yes, guys do not lie, nothing complicated, even hello world wrote for us.

Simple blog

But we need something fun. Let's write, for example, a simple blog.
Disclaimer: вообще-то meteor (как и node.js) предназначен в первую очередь для создания сложных одностраничных приложений и в обычном блоге многие его возможности останутся неиспользованными.


Meteor professes the ideology of "One code on the server and client." This is expressed in the fact that the code from all .js files in the project (.coffee is also valid when installing the corresponding smart package) except for that in the subdirectories server, clientand they publicare executed both on the server side in node.js (via fiber), and in user’s browser.
The code from the server directory can be executed only on the server, from clientthe client, and in publicwhere static files are stored, it should not exist at all. Also at our disposal are logical variables Meteor.isClientand Meteor.isServer, which take different values ​​depending on where the code is executed.
The same applies to .css and .html files - they can be scattered throughout the project. Meteor will find and assemble them together.
There is another special test directory, from which nothing is loaded by default by default.
It is also necessary to understand that meteor is such a hodgepodge of many technologies, so there can be very little pure javascript. jQuery and Underscore run the show here. No need to install anything, just write as you are used to. Handlebars , an advanced version of Mustache, is used as a template engine . Communication with the MongoDB database (support of other options is also promised) is carried out using Minimongo ( apparently promises a pleasant work with this wrapper).
In this example, Foundation will be used as the css framework , which I like better than the similar Twitter Bootstrap, but this is a matter of taste.

Output records

Let's start by accessing the database. On the server in the .js file, create a new collection in which all our records will be stored.
Posts = new Meteor.Collection("posts");

We also set the initial values:
  Meteor.startup(function () { // этот код исполняется сразу после запуска
    if (Posts.find().count() === 0) {
      var posts = [
        title: "Title one",
        text: "Lorem ipsum dolor sit amet, consectetur adipisicing elit. Et iure porro sunt repudiandae amet saepe asperiores commodi repellendus hic accusamus obcaecati ipsum modi magnam nulla magni vitae ea voluptates dignissimos!",
        published: (new Date()).toLocaleTimeString()
        title: "Title two",
        text: "Lorem ipsum dolor sit amet, consectetur adipisicing elit. Culpa natus mollitia similique accusamus minus harum magnam eum pariatur rerum fugit ducimus sapiente asperiores quidem molestias repudiandae consequuntur repellendus dolorum placeat.",
        published: (new Date()).toLocaleTimeString()
      for (var i = 0; i < posts.length; i++) {
          title: posts[i].title,
          text: posts[i].text,
          published: posts[i].published,

Then create a Handlebars record display template and call it stream:
{{> stream}}

... and derive the initial values ​​through it. = function () {
    return Posts.find({}, {sort: {published: -1}});

Thus, we brought all the entries to the main page.

Adding and removing entries

To add your entries, first create a new editor template with the appropriate form for adding:

The next step is to create an event handler that, when you click on the button, will add the contents of the fields to the database. The added information will be immediately displayed to all customers.{
    "click #submit-post": function() {
      var published_date = new Date();
        title: document.getElementById("title-area").value,
        text: document.getElementById("editor-area").value,
        published: published_date.toLocaleTimeString()

To remove unnecessary entries from the database, we also create a new event handler:{
    "click .remove": function () {

... which will be attached to the corresponding button in the recording template.

Thus, we got the simplest application in several lines, with the functionality of displaying, adding and deleting records.
It is worth noting that due to the "reactivity" of the meteor, all database operations will be instantly displayed by all users. To prevent this behavior, you must remove the package responsible for this case:
meteor remove autopublish

An example is simple, if not primitive. But even he shows that thanks to the convenient interface provided by this framework, a person who is far enough from web development can use technologies that only a few years ago were available only to highly qualified developers (sockets, dynamic updates, js on the server, document-oriented databases data).
However, according to skepticism, in comments to other posts about Meteor we can say that not everyone likes such a radical simplification. Representatives of the "old guard" grumble: " Another framework!" Not canonical. Only assembler, only hardcore! ". As a sociologist, it seems to me that this position is to some extent a consequence of the unwillingness to lose their exclusive status as professionals working with node.js.
However, I am sure that moving towards comprehensibility and simplification is an undoubted benefit. Professionals, if they really are, can stand out in a growing market. And many IT lovers who work in other areas, and therefore do not have time to translate their ideas in this field, will receive a wonderful tool for creativity and will probably create many web applications that solve their highly specialized problems, which a professional developer may not know about.
PS: if the community is interested in this topic, you can write another one or two articles describing the implementation of additional blog functionality: editing posts, adding tags and categories, creating user accounts, delimiting access rights.

Also popular now: