Category Archives: Node

使用PM2在生产环境部署nodejs项目

本地开发时,可以直接敲node example.js或者运行在package.json文件中定义的命令(比较常见的有npm run dev, npm run start…)。但是线上生产环境是不可以直接这样子跑程序的,因为一旦程序出错,这个服务就挂了。为了让线上生产环境里的项目能用长期处于可用状态,我们可以使用PM2这个包。

官方对P(process)M(manager)2的介绍:

PM2 is a production process manager for Node.js applications with a built-in load balancer. It allows you to keep applications alive forever, to reload them without downtime and to facilitate common system admin tasks.

具体用法(比如我个人一个用node写的博客项目,其程序入口文件是./bin/www),那么我要执行的步骤如下:

一、全局安装pm2

二、用pm2启动node项目

至此,简单的nodejs项目生产环境部署就完成了。

通过apache代理,将node服务与指定域名进行绑定

这篇文章应该算《CentOS7-配置Apache虚拟主机》的姊妹篇-_-。我用的操作系统是CentOS7,上网找了很多资料和代码demo,要么是用nginx而非apache实现请求转发的,要么就是通过apache将某个url路径与node服务进行绑定的。所以记录一下如何通过apache代理将node服务与指定域名进行绑定的方法,方便以后查阅。之所以不用nginx,是因为我的vps只有2g内存,已经用了一半内存了,鬼知道以后会不会还要装什么乱七八糟的东西,现在能少装些东西就少装些东西-_-。

建议先看一下姊妹篇文章,然后再看下面的内容,不然会不知所云的。

假设本地node服务使用的端口号为18080,要绑定的域名为www.example.com,需进行如下操作:

一、确认已在Apache配置文件(/etc/httpd/conf/httpd.conf)末尾添加如下代码:

二、/etc/httpd/sites-available/example.com.conf文件的内容如下:

三、在/etc/httpd/sites-enabled/下创建指向/etc/httpd/sites-available/example.com.conf的快捷方式。

四、重启Apache服务。

五、Well done.

花生壳内网映射导致请求失败

有段时间,不知何故,本地的请求通过node环境中的一个叫http-proxy-middleware的包转发本地请求到别人通过花生壳映射的内网后,总是请求失败,会报错:ORAY-ERROR-3。这个显然不会是朋友那边本地服务器的问题,因为这个服务放在公网上时,里面的服务都是可以用的。

我用的是vue-cli脚手架配套的webpack模版。经过尝试,发现只要修改一下转发的请求头里的Host字段即可。具体要修改的文件为:/build/dev-server.js,需要修改的地方见下面的代码:

代码中config.hostUsed即为花生壳内网映射时对应的外网地址,这个值不需要包含http或https这种协议字符,只需要’www.example.com’这部分就可以了。

Recursion in EJS and Handlebars

Once in a frontend project using handlebars as the template, I can use code like the following code snippet to realize recursion:

So, I think probably recursion effect can also be implemented in EJS template. And after some testing, the answer is yes, and a sample code snippet is as below:

Keep Nodejs Program Running after Closing SSH

I happened to find that although my Nodejs program can run normally when I started it through SSH. If I close the SSH connection, then I can no longer visit corresponding frontend file through my browser. Oh my god, the program was closed automatically the time I closed the SSH connection. Here is the solution to the problem:

Note that the command “npm run start” is the command to start my Nodejs program, it may differ from your program, and if so, you should replace the command “npm run start” with your program-starting command.

Deploy Nodejs Project on CentOS

The server is php-and-mysql-available with the help of Webmin (a web-based unix system management tool). So there is no need for me to install mysql myself. What’s more, I have already a nodejs program available to run in my laptop (window OS) and the Baidu BAE (unix OS). Due to preassembled php program, the 80 port is employed and the root path for front-end files under 80 port is located in /home/username/public_html. To avoid confusion between php projects and nodejs projects, I created a new folder named “node-server” under /home/orzzone/ path. In a conclusion, I uploaded my Nodejs project files to the path ‘/home/username/node-server’.

After uploading operation was completed, I changed the current working directory to the path ‘/home/username/node-server’, and ran command “npm i” to install dependencies specified in package.json file. With all dependencies installed, I ran command “npm run start” to start my project which uses port 18080 instead of 80. All seems to go well with no error information jumped to the screen of my command line tool. But when I visited a api url through my web browser, it responsed with error information saying something as below:

Oh, what happend? The same mysql login parameter was availble for use in both my laptop and the online server provided by Baidu BAE. So I was sure that there is no error in the mysql login parameter. After half a day’s time-wasting, I found the problem. There were two anonymous mysql accounts! After I deleted the two accounts, the online nodejs program was available to communicate with mysql database normally.

A good day.

Install Nodejs via package manager on CentOS

I installed Nodejs according to the Nodejs official online instructions.

My operation system is Centos 6.5 64bit. Memory is 1.95GB. And disk space is 15 GB.

Installing result is as below:

Instructions:

  1. Run as root on CentOS, for Node.js v6 LTS:

  1. Then install, as root:

  1. Check

Reference:

  • https://nodejs.org/en/download/package-manager/#enterprise-linux-and-fedora

Install Node.js

Node.js Install Location

After you install Node.js by using an installer from the Node.js website. You’ll see some executable files and the node_modules folder:

  • node.exe: This file starts a Node.js JavaScript engine. If you pass in a JavaScript file location, Node.js executes that script. If no target avaScript file is specified, a script prompt allows you to execute JavaScript code directly from the console.
  • npm.cmd: You use this command to manage the Node.js packages.
  • node_modules: This folder contains the installed Node.js packages. These packages act as libraries that extend the capabilities of Node.js.

Verifying Node.js Executables

Open a command prompt and execute the following command to bring up a Node.js VM:

node

Then, you are now at the Node.js prompt. Execute the following to write “Hello World” to the screen:

console.log(”Hello World);

After you see “Hello World” written to the console screen, exit the console by pressing Ctrl+C in Windows.

Next, verify that the npm command is working by executing the following command at the command prompt:

npm version

What you see may be similar to the following:

{npm: ‘3.3.12’,
area: ‘1.10.1-DEV’,
http_parser: ‘2.6.0’,
icu: ‘56.1’,
modules: ’47’,
node: ‘5.2.0’,
openssl: ‘1.0.2e’,
uv: ‘1.7.5’,
v8: ‘4.6.85.31’,
zlib: ‘1.2.8’ }

Selecting a Node.js IDE

For example, Eclipse has some great Node.js plugins, and the WebStrom IDE by IntelliJ has some good features for Node.js built in.

You can use any editor you want to generate your Node.js web applications. In reality, all you need i a decent text editor. Almost all he code you will be generating will be .js, .json, .html, and .css. So pick the editor you feel the most comfortable using to write those types of files.

Working with Node.js Packages

One of the most powerful features of the Node.js framework is the ability to easily extend it with additional Node Packaged Modules (NPMs), using the Node Package manager (NPM).

A Node Packaged Module is a packaged library that can easily be shared, reused, and installed in different projects. There are many different modules available for a variety of purposes. For example, the Mongoose module provides an ODM for MongoDB, Express extends Node’s HTTP capabilities, and so on.

Node.js modules are created by various third-party organizations to provide important features that Node.js lacks out of the box. This community of contributors is very active in ading and updating modules.

Each Node Packaged Module includes a package.json file that defines the packages. The package.json file includes informational metadata such as the name, version, author, and contributors, as well as control metadata such as dependencies and other requirements that the Node Package manager will use when performing actions such as installation and publishing.

Using the Node Package Manager

The simplest way to really explain the Node Package Manager is to list some of the command-line options and what they do. The following is a list of the Node Package Manager commands (with express as the package, where appropriate).

search: Finds module packages in the repository.

npm search express

install: Installs a package either using a package.json file from the repository or from a local location.

npm install

npm install express

npm install express@0.1.1

npm install ../tModule.tgz

install -g: Installs a package in a globally accessible location.

npm install express -g

remove: Removes a module.

npm remove express

pack: Packages the module defined by the package.json file into a .tgz file.

npm pack

view: Displays module details.

npm view express

publish: Publishes the module defined by a package.json file to the registry

npm publish

unpublish: Unpublishes a module you have published

npm unpublish myModule

owner: Allows you to add, remove, and list owners of a package in the repository

npm add bdayley myModule

npm rm bdayley myModule

npm ls myModule

Using package.json

All Node modules must include a package.json file in their root directory. package.json is a simple JSON text file that defines a module, including dependencies. The package.json file can contain a number of different directives to tell the Node Package Manager how to handle the module.

Here is an example of a package.json file with a name, version, description, and dependencies:

{
“name”: “my_module”,
“version”: “0.1.0”,
“description”: “a simple node.js module”,
“dependencies”: {“express”: “latest”}
}

The only required directives in the package.json file are name and version; the rest depend n what you would like to include. The following describes the most common directives.

name: Unique name of package.

“name”: “camelot”

preferGlobal: Indicator that the module prefers to be installed globally.

“preferGlobal”: true

version: Version of the module.

“version”: 0.0.1

author: Author of the project.

“author”: “author@example.com”

description: Text description of module.

“description”: “a silly place”

contributors: Additional contributors to the module.

“contributors”: {{“name”: “gwen”, “email”: “gwen@example.com”}}

bin: Binary to be installed with the project.

“bin”: {“excalibur”: “./bin/excalibur”}

scripts: Parameters tat execute console apps when launching node.

“scripts”: {“start”: “node./bin/excalibur”, “test”: “echo testing”}

main: The main entry point for the app which can be a binary or a .js file.

“main”: “./bin/excalibur”

repository: The repository type and location of the package.

“repository”: {“type”: “git”, “location”: “http://???.com/c.git”}

keywords: Keywords that show up in the npm search

“keywords”: [“swallow”, “unladen”]

dependencies: Modules and versions this module depends on; you can use the * and x wildcards (通配符、万用字符).

“dependencies”: {“express”: “latest”, “connect”: “2.x.x”, “cookies”: “*”}

engines: The version of node this package works with.

“engines”: {“node”: “>=0.6”}

A great way to use package.json files is to automatically download and install the dependencies for your Node.js app. All you need to do is create a package.json file in the root of your project code and add necessary dependencies to it. For example, the following package.json file requires the express module as a dependency:

{
“name”: “my_module”,
“version”: “0.1.0”,
“dependencies”: {“express”: “latest”}
}

Then you run the following command from the root of your package, and the express module is automatically installed:

npm install

Notice that no module is specified in the command npm install. That is because npm looks for a package.json file by default. Later, as you need additional modules, all you need to do is add those to the dependencies directive and then run npm install again.

Reference: Node.js, MongoDB, and AngularJS Web Development.