×
Community Blog Getting Started with Node.JS on Alibaba Cloud

Getting Started with Node.JS on Alibaba Cloud

In this article, we will look at the basics of Node.JS as well as explore its various features for front-end development on Alibaba Cloud.

By Alex Mungai Muchiri, Alibaba Cloud Tech Share Author. Tech Share is Alibaba Cloud's incentive program to encourage the sharing of technical knowledge and best practices within the cloud community.

The Node.JS JavaScript framework was developed by Ryan Dahl in 2009 and is suitable for rapid development of highly scalable network applications. It is a server-side platform that is based on the V8 Engine (Chrome JE). It is particularly useful when building data-intensive real-time web applications because of its event-driven non-blocking I/O model. Its performance on distributed devices is impeccable for its lightweight and efficient architecture. Notably, Node.js is an open source, a cross-platform environment that runs across OS X, Microsoft Windows, and Linux. Developers use it for server-side and network application development.

The Node.js applications run in the Node.js runtime and its cross-platform compatibility is due to the JavaScript used in writing the applications. You will also find it useful that Node.js is supported by an extensive community that supplies libraries and JavaScript modules that make development much easier.

In short: Node.js = Runtime Environment + JavaScript Library

In this article, we will learn how to use Node.JS on Alibaba Cloud by installing it on an Elastic Compute Service (ECS) instance.

Prominent Node.JS Features

IT experts, especially software architects would find Node a very useful framework for their day-to-day activities. The most notable features include:

Node Is Asynchronous and Event-Driven

Node.js libraries employ asynchronous non-blocking APIs, which means that it uses both calling and notification mechanisms. In detail, a server calls an API and moves to the nest one to obtain a notification instead of waiting for a response using the Node.js Events that facilitates the server in getting a response.

Node Is Very Fast

The Node.js execution of code is excellently speedy since it is based on the Chrome V8 engine.

Node Is Scalable

The Node.js execution model is single-threaded coupled with event looping. However, it is highly scalable since the server responds in a non-blocking way using the events mechanism. Compared to traditional models, servers running Node.js create unlimited threads to handle requests. The single program used by Node can service more requests compared to Apache HTTP server and other traditional models.

No Buffering

Node.js applications have their data in chunked outputs, which implies that there is absolutely no buffering.

Built on both the V8 Chrome engine and ECMAScript, Node.js is compatible with most front-end objects, functions and methods served in JavaScript. Furthermore, Node.js is open source under the MIT license.

Installing Node.JS

Installing Node.js is easy, all you need is visit their website and follow through with this tutorial.

Read-Eval-Print Loop

Node.JS employs the read-eval-print loop as the case in most programming languages and platforms in existence. The $ node command opens this console of Node, which changes the prompt to > when activated to allow running of JavaScript in the way that Chrome Developer Tools console works. However, Node.js is slightly different implementations of ECMAScript such as the ({}+{}) but largely there are minimal differences.

The Node.js console allows us to use JavaScript without any difficulty, save for a few exceptions.

How to Launch Node.js Scripts

If you need to start a Node.js script that is stored in a file, you will run the command below:

$ node filename, e.g., $ node program.js.

It also incorporates an -e function to run quick statements in line with JavaScript/Node.js such as:

$ node -e "console.log(new Date());"

Process Information in Node.js

All running Node.js scripts are essentially processes. For instance, to output running Node.js programs that are currently running on a computer, we would use the script below:

ps aux | grep 'node'

There is also the process object, which allows programmers to access information using a simple line of code such as:

node -e "console.log(process.pid)"

How to Access Global Scope in Node.js

Everything in JavaScript is always in its global scope, which is a drawback of the framework. However, Node.js has a stark variation with JS on this front, whereby everything is maintained as local by default. The global object handles the need to access all global objects. It also allows the exporting of objects in an explicit format. In the end, we have both global and process objects that would constitute JavaScript front-end browser window objects. Node.js also does not support the DOM webpage document object.

How to Export and Import Modules

JavaScript does not provide for a way to include models, which means that scripts have to be linked using HTML that lags when it comes to dependency management. The AJAX-y method resolves that problem for CommonJS and RequireJS. It is the same concept that Node.js has employed to deal with the issue.

The method of exporting Node.js objects is as follows:

exports.name = object;, e.g., 
var messages = {
  find: function(req, res, next) {
  ...
  },
  add: function(req, res, next) {
  ...
  }, 
  format: 'title | date | author'
}
exports.messages = messages;

If we had a specified path to a file that we wanted to export script, say route/messages.js, we can use the following line:

var messages = require('./routes/messages.js');

But sometimes it works better to invoke a constructor when attaching properties to Express.js applications. In such a situation, we include a module.exports process in our code as shown:

module.exports = function(app) {
  app.set('port', process.env.PORT || 3000);
  app.set('views', __dirname + '/views');
  app.set('view engine', 'jade');
  return app;
}

We also need to revisit the file containing the aforementioned module and include the following:

...
var app = express();
var config = require('./config/index.js');
app = config(app);
...

It is common that wrong file paths are entered when including modules, so be watchful of that. There is an alternative and more precise version of the above code that would be executed as in the below:

var = express(); require('./config/index.js')(app);.

Notably, core Node.js modules, as well as those in the node_modules folder, do not require a path, just the name. In all other cases, which may or may not include a file extension, use a ".".

var keys = require('./keys.js'),
  messages = require('./routes/messages.js');

Additionally, Node also allows the use of longer looking statements that include __dirname and path.join(). For instance, we could state: require(path.join(__dirname, ,'routes', 'messages'));

In the case above, require() could be a pointer to a folder, in which case Node.js will try to decode index.js any file in it.

Buffer in Node.js

Node.js has four primitives which include: number, boolean, string, and RegExp. The buffer is an over-the-top addition to these primitives as well as any other objects contained in front-end JavaScript. They allow for speedy data storage and all used in nearly all circumstances such as reading file systems and receiving packets.

__dirname versus process.cwd

In Node.js, the process.cwd denotes an absolute path to a process running the script, whereas __dirname represents the absolute path to a file. These two items are not necessarily similar if a separate folder was used when initializing the program (such as $ node ./code/program.js.)

Other Useful Utilities

While Node.js framework was designed to be minimalistic, it has some very useful utilities including:

  1. URL
  2. Crypto
  3. Path
  4. String Decoder

Our tutorial article employs the path.join technique

Handling File Systems in Node.js

Node reads from file systems using its fs module that uses either the async and sync methods for the operation. However, the async method is more popular among developers. For instance, we could use fs.readFile:

var fs = require('fs');
var path = require('path');
fs.readFile(path.join(__dirname, '/data/customers.csv'), {encoding: 'utf-8'}, function (err, data) {
  if (err) throw err;
  console.log(data);
});

To be able to write to a file system, the async method goes as follows:

var fs = require('fs');
fs.writeFile('message.txt', 'Hello World!', function (err) {
  if (err) throw err;
  console.log('Writing is done.');
});

How to Stream Data in Node.js

The streaming process simply entails data processing by an application while it continuously trickles in. It is useful when dealing large data sets as in database migrations or video content. A simple stream function in Node.js could be written as follows:

var fs = require('fs');
fs.createReadStream('./data/clients.csv').pipe(process.stdout);

Using NPN to Install Node.js modules

NPN is a very handy tool for Node.js that allows very advanced package management. NPN is able to traverse the working tree and figure out what project is current when the npm install command is used. To begin with, you will need one of the following:

  1. The package.json file
  2. The node_modules folder

Run $ npm install name to install modules locally, e.g. $ npm install surprise; in Node.js, we shall additionally include the line: var surprise = require(surprise);.

In NPN, all dependencies are locally maintained and we can, therefore, maintain several versions of modules locally for different entities that rely on either. For instance, we could have a situation where Module 1 uses Module 2 v1 while module 3 uses module 2 v2. All the copies will be locally availed instead of the common global default.

Remember, do not include in the Git repository a node_modules folder any project needed in other apps, only include for applications that could be deployed.

Hello World

We are going to use the HTTP Node.js module in this example, which is a network application of the framework. It's a simple function to create an object in our server, state the request handler and respond to the recipient with some data.

var HTTP = require('HTTP');
http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello World\n');
}).listen(1332, '127.100.10.1');
console.log('Server running at http://127.100.10.1:1332/');]

In this case, our req and res parameters contain all instructions concerning the HTTP requests and responses and could be used in buffer for streaming (see above).

Catching Bugs in Node.js

console.log() is by far the most suitable Node.js debugger. You could also download node-inspector for a cleaner debug interface or simply use $ node debug program.js for the procedure.

Dealing with Callbacks in Node.js

With callbacks, Node.js code runs asynchronously. If you are unfamiliar with the technique, see the example in the below:

fs.readdir(source, function(err, files) {
  if (err) {
    console.log('Error finding files: ' + err)
  } else {
    files.forEach(function(filename, fileIndex) {
      console.log(filename)
      gm(source + filename).size(function(err, values) {
        if (err) {
          console.log('Error identifying file size: ' + err)
        } else {
          console.log(filename + ' : ' + values)
          aspect = (values.width / values.height)
          widths.forEach(function(width, widthIndex) {
            height = Math.round(width / aspect)
            console.log('resizing ' + filename + 'to ' + height + 'x' + height)
            this.resize(width, height).write(destination + 'w' + width + '_' + filename, function(err) {
              if (err) console.log('Error writing file: ' + err)
            })
          }.bind(this))
        }
      })
    })
  }
})

Summary

Node is your perfect technology for:

  1. I/O bound apps
  2. Apps for data streaming
  3. Data Intensive Real-time Applications (DIRT)
  4. JSON APIs based apps
  5. Single page apps

Hope you enjoyed the tutorial and that you find this sufficiently capable of getting you acquainted with the Node.js framework for front-end development on Alibaba Cloud. Don't have an Alibaba Cloud account yet? Sign up for an account and try over 40 products for free worth up to $1200. Get Started with Alibaba Cloud to learn more.

1 3 1
Share on

Alex

22 posts | 2 followers

You may also like

Comments

Raja_KT March 2, 2019 at 4:43 am

Good one with nice examples.