https://i.imgur.com/3yj1n6N.png

NodeBB является дискуссионной площадкой нового поколения, которая использует веб-сокеты для мгновенного взаимодействия и уведомлений в режиме реального времени. Форум NodeBB имеет множество современных функций, включая интеграцию социальных сетей и потоковые обсуждения.

NodeBB это проект с открытым исходным кодом, который может быть форкнут на GitHub. Вы можете внести свой вклад в этот проект - помочь с переводом, рассказать о проекте друзьям, подать запрос на включение в проект сделанных Вами изменений.

Содержание

Установка NodeBB

Установка NodeBB в ОС

Следующие пошаговые руководства помогут Вам установить и запустить NodeBB.

Примечание

Если Вашей операционной системы нет в списке, пожалуйста, не стесняйтесь запросить создание руководства на нашем форуме или, что даже еще лучше, сделайте руководство сами и разместите его здесь.

Arch Linux

Во-первых, мы установим наш стек базового программного обеспечения. Не забудьте в начале выполнить команду pacman -Syu, для того чтобы обновить пакеты и проверить синхронизация с репозиториями.

$ sudo pacman -S git nodejs npm redis imagemagick

Если Вы хотите использовать MongoDB, LevelDB или другую базу данных вместо Redis, пожалуйста посмотрете раздел Настройка Баз Данных.

Далее клонируем репозиторий:

$ git clone -b v0.7.x https://github.com/NodeBB/NodeBB.git nodebb

Получаем все зависимости, необходимые для NodeBB:

$ cd nodebb
$ npm install

Инициируем скрипт установки, запустив приложение с флагом setup:

$ ./nodebb setup

Настройки по умолчанию сделаны для локального сервера, который работает на дефолтном порту с базой данных redis на этой же машине и тоже на дефолтном порту.

Наконец, мы запускаем форум.

$ ./nodebb start

NodeBB можно запускать с помощью вспомогательных программ, таких как supervisor и forever. Посмотрите на возможные варианты здесь.

Ubuntu

Первым делом установим необходимое базовое программное обеспечение:

$ sudo apt-get install git nodejs nodejs-legacy npm redis-server imagemagick build-essential

Если Вы хотите использовать MongoDB, LevelDB или другую базу данных вместо Redis, пожалуйста посмотрете раздел Настройка Баз Данных.

Если менеджер пакетов может установить версию Node.js только ниже 0.8 (это относится к Ubuntu 12.10, 13.04), используйте команду ``node –version`` для определния версии Node.js:

$ sudo add-apt-repository ppa:chris-lea/node.js
$ sudo apt-get update && sudo apt-get dist-upgrade

Если Вы хотите установить Node.js v0.11, используйте репозиторий ppa:chris-lea/node.js-devel. Npm устанавливается вместе с nodejs

Затем клонируем этот репозиторий:

$ git clone -b v0.7.x https://github.com/NodeBB/NodeBB.git nodebb

Получаем все необходимые зависимости для NodeBB:

$ cd nodebb
$ npm install --production

Запускаем Веб-установщик NodeBB и продолжаем установку в браузере по адресу http://127.0.0.1:4567.

$ npm start

Альтернативно: Инициируйте скрипт настройки, запустив приложение с флагом setup:

$ ./nodebb setup

Настройки по умолчанию сделаны для локального сервера, который работает на дефолтном порту с базой данных redis на этой же машине, которая тоже слушает порт по умолчанию.

Теперь запускаем форум.

$ ./nodebb start

NodeBB можно запускать с помощью вспомогательных программ, таких как forever. Посмотрите на возможные варианты здесь.

Debian

The current Ubuntu guide is not completely compatible with Debian and there are some specificities and especially the NodeJS installation, and how to get latest Redis.

Requirements

NodeBB requires these software to be installed:

  • Node.js at least 0.10 and greater
  • Redis, version 2.6 or greater
  • cURL installed, just do sudo apt-get install curl in order to install it
Node.js installation

Debian 7 and Debian 6 and older doesn’t have nodejs packages included by default, but there are some solutions to install Node.js on your Debian distribution.

Wheezy Backport :

This solution is ONLY for Debian 7, simply run the following as root :

$ echo "deb http://ftp.us.debian.org/debian wheezy-backports main" > /etc/apt/sources.list.d/wheezy-backports.list
$ apt-get update

To install Node.js + NPM, run this :

$ apt-get install nodejs-legacy
$ curl -L --insecure https://www.npmjs.org/install.sh | bash

The following install a Node.js version who is greater than 0.8 (at 29 March 2014 : 0.10.21)

Compiling from the source :

This solution is for Debian 6 (Squeeze) and greater, in order to install NodeJS, run this as root :

$ sudo apt-get install python g++ make checkinstall
$ src=$(mktemp -d) && cd $src
$ wget -N http://nodejs.org/dist/node-latest.tar.gz
$ tar xzvf node-latest.tar.gz && cd node-v*
$ ./configure
$ fakeroot checkinstall -y --install=no --pkgversion $(echo $(pwd) | sed -n -re's/.+node-v(.+)$/\1/p') make -j$(($(nproc)+1)) install
$ sudo dpkg -i node_*
Get latest Software via DotDeb

Dotdeb is a repository containing packages to turn your Debian boxes into powerful, stable and up-to-date LAMP servers.

  • Nginx,
  • PHP 5.4 and 5.3 (useful PHP extensions : APC, imagick, Pinba, xcache, Xdebug, XHpro..)
  • MySQL 5.5,
  • Percona toolkit,
  • Redis,
  • Zabbix,
  • Passenger…

Dotdeb supports :

  • Debian 6.0 “Squeeze“ and 7 “Wheezy“
  • both amd64 and i386 architectures
Debian 7 (Wheezy) :

For the complete DotDeb repositories :

$ sudo echo 'deb http://packages.dotdeb.org wheezy all' > /etc/apt/sources.list.d/dotdeb.list
$ sudo echo 'deb-src http://packages.dotdeb.org wheezy all' >> /etc/apt/sources.list.d/dotdeb.list

After this, add the following GPC keys :

$ wget http://www.dotdeb.org/dotdeb.gpg
$ sudo apt-key add dotdeb.gpg

And update your package source :

$ sudo apt-get update
Debian 6 (Squeeze)

For the complete DotDeb repositories :

$ sudo echo 'deb http://packages.dotdeb.org squeeze all' >> /etc/apt/sources.list
$ sudo echo 'deb-src http://packages.dotdeb.org squeeze all' >> /etc/apt/sources.list

After this, add the following GPC keys :

$ wget http://www.dotdeb.org/dotdeb.gpg
$ sudo apt-key add dotdeb.gpg

And update your package source :

$ sudo apt-get update
Installing NodeBB

Now, we have NodeJS installed and Redis ready to be installed, run this command for install the base software stack :

$ apt-get install redis-server imagemagick git build-essential

Next clone this repository :

$ cd /path/to/nodebb/install/location
$ git clone -b v0.7.x https://github.com/NodeBB/NodeBB.git nodebb

Now we are going to install all dependencies for NodeBB via NPM :

$ cd /path/to/nodebb/install/location/nodebb (or if you are on your install location directory run : cd nodebb)
$ npm install

Install NodeBB by running the app with –setup flag :

$ ./nodebb setup
  1. URL of this installation is either your public ip address or your domain name pointing to that ip address.
    Example: http://0.0.0.0 or http://example.org
  2. Port number of your NodeBB is the port needed to access your site:
    Note: If you do not proxy your port with something like nginx then port 80 is recommended for production.
  3. If you used the above steps to setup your redis-server then use the default redis settings.

And after all.. let’s run the NodeBB forum

$ ./nodebb start

Note: If you NodeBB or your server crash, your NodeBB instance will not reboot (snap), this is why you should take a look at the other way to start your NodeBB instance with helper programs such as supervisor and forever, just take a look here it’s simple as a click!

Extras, tips and Advice

You should secure your NodeBB installation, take a look here.

You should use Nginx (or similar) in order to reverse proxy your NodeBB installation on the port 80, take a look here

SmartOS

Requirements

NodeBB requires the following software to be installed:

  • Node.js (version 0.10 or greater, instructions below).
  • Redis (version 2.6 or greater, instructions below) or MongoDB (version 2.6 or greater).
  • nginx (version 1.3.13 or greater, only if intending to use nginx to proxy requests to a NodeBB server).
Server Access
  1. Sign in your Joyent account: Joyent.com

  2. Select: Create Instance

  3. Create the newest smartos nodejs image.

    Note: The following steps have been tested with images: smartos nodejs 13.1.0 smartos nodejs 13.2.3

  4. Wait for your instance to show Running then click on its name.

  5. Find your Login and admin password. If the Credentials section is missing, refresh the webpage.

    Example: ssh root@0.0.0.0 A#Ca{c1@3

  6. SSH into your server as the admin not root: ssh admin@0.0.0.0

    Note: For Windows users that do not have ssh installed, here is an option: Cygwin.com

Installation
  1. Install NodeBB’s software dependencies:

    $ sudo pkgin update
    $ sudo pkgin install scmgit nodejs build-essential ImageMagick redis
    

    If any of those failed to install then:

    $ pkgin search *failed-name*
    $ sudo pkgin install *available-name*
    
  2. If needed setup a redis-server with default settings as a service (automatically starts and restarts):

    If you want to use MongoDB, LevelDB, or another database instead of Redis please look at the Configuring Databases section.

    Note: These steps quickly setup a redis server but do not fine-tuned it for production.

    Note: If you manually ran redis-server then exit out of it now.

    $ svcadm enable redis
    $ svcs svc:/pkgsrc/redis:default
    

    Note: If the STATE is maintenance then:

    $ scvadm clear redis
    

    - To shut down your redis-server and keep it from restarting:

    $ scvadm disable redis
    

    - To start up your redis-server and have it always running:

    $ scvadm enable redis
    
  3. Move to where you want to create the nodebb folder:

    $ cd /parent/directory/of/nodebb/
    
  4. Clone NodeBB’s repository (you may replace the ending nodebb with a different folder name):

    $ git clone -b v0.7.x https://github.com/NodeBB/NodeBB.git nodebb
    
  5. Install NodeBB’s npm dependencies:

    $ cd nodebb
    $ npm install
    
  6. Run NodeBB’s setup script:

    $ ./nodebb setup
    
    1. URL used to access this NodeBB is either your public ip address from your ssh Login or your domain name pointing to that ip address.

      Example: http://0.0.0.0 or http://example.org

    2. Port number of your NodeBB is the port needed to access your site:

      Note: If you do not proxy your port with something like nginx then port 80 is recommended for production.

    3. Please enter a NodeBB secret - Do not email this or post publicly.

    4. IP or Hostname to bind to - Use default unless your server requires otherwise.

    5. If you used the above steps to setup your redis-server then use the default redis settings.

  7. Start NodeBB process manually:

    Note: This should not be used for production but instead create a deamon manually, use Forever, or use Supervisor. Take a look at the options here.

    $ node app
    
  8. Visit your app!

    Example: With a port of 4567: http://0.0.0.0:4567 or http://example.org:4567

    Note: With port 80 the :80 does not need to be entered.

Note: If these instructions are unclear or if you run into trouble, please let us know by filing an issue.

Upgrading NodeBB

Note: Detailed upgrade instructions are listed in Upgrading NodeBB.

Windows 8

Необходимое программное обеспечение

В начале установим следующие программы:

Возможно Вам придется перезагрузить компьютер.

Запуск NodeBB

Запускаем Redis Server

Примечание

Расположение Redis Server по умолчанию:

C:\Program Files (x86)\Redis\StartRedisServer.cmd

Откройте Git Shell и введите следующие команды. Клонируем репозиторий NodeBB:

git clone -b v0.7.x https://github.com/NodeBB/NodeBB.git

Заходим в каталог:

cd NodeBB

Устанавливаем зависимости:

npm install

Запускаем интерактивную установку:

node app.js --setup

Можно оставить все параметры по умолчанию.

Готово! После установки, запустите:

node app.js

Можно проверить работу форума по адресу http://127.0.0.1:4567/

Разработка под Windows

Каждый раз когда Вы делаете изменения, выключение и перезагрузка NodeBB будет головной болью. Для начала установим supervisor:

npm install -g supervisor

Откройте bash:

bash

И запустите NodeBB в режиме “watch”:

./nodebb watch

Эта команда запустит NodeBB в режиме разработчика, будет отслеживать изменения файлов и автоматически перезапускать форум.

OSX Mavericks

Необходимое программное обеспечение

В начале установим следующие программы:

Запуск NodeBB

Установите redis с homebrew:

brew install redis

Запускаем redis server, введите в терминале:

redis-server

Клонируем репозиторий NodeBB:

git clone -b v0.7.x https://github.com/NodeBB/NodeBB.git

Заходим в каталог:

cd NodeBB

Устанавливаем зависимости:

npm install

Запускаем интерактивную установку:

./nodebb setup

Можно оставить все опции по умолчанию.

Готово! Запускаем после установки

./nodebb start

Можно проверить работу форума по адресу http://localhost:4567/

CentOS 6/7

Во-первых, мы должны убедиться, что наш CentOS обновлен, мы можем сделать это, используя следующую команду:

yum -y update

**Если Вы используете CentOS 7, то Вам необходимо установить epel release, это можно сделать выполнив следующую команду:

yum -y install epel-release

Теперь мы установим базовое программное обеспечение:

yum -y groupinstall "Development Tools"
yum -y install nodejs git redis ImageMagick npm

Если Вы хотите использовать MongoDB, LevelDB или другую базу данных вместо Redis, пожалуйста посмотрете раздел Настройка баз данных.

Далее клонируем репозиторий:

cd /path/to/nodebb/install/location
git clone -b v0.7.x https://github.com/NodeBB/NodeBB nodebb

**Примечание: Для клонирования master-ветки Вы можте использовать такую же команду, убрав параметр “-b”.

Получаем все зависимости, необходимые для NodeBB, после клонирования репозитория:

cd nodebb
npm install

Инициируем скрипт установки, запустив приложение с флагом setup:

./nodebb setup

Настройки по умолчанию сделаны для локального сервера, который работает на дефолтном порту с базой данных redis на этой же машине и тоже на дефолтном порту.

Наконец, мы запускаем форум.

./nodebb start

NodeBB можно запускать с помощью вспомогательных программ, таких как forever forever. Посмотрите на возможные варианты здесь.

Installing NodeBB on the Cloud

The following are step-by-step guides to help you get up and running on the cloud using popular PaaS solutions.

Примечание

If the PaaS solution of your choice is not listed here, please feel free to request a guide on our community or even better yet, submit one here.

Cloud 9 IDE

The following are installation instructions for the Cloud 9 web based IDE.

Step 1: Clone NodeBB into a new workspace from GitHub. You can use the following command from the terminal:

git clone -b v0.7.x https://github.com/NodeBB/NodeBB.git nodebb

The nodebb command after the git url will create a file called nodebb so you have to CD into the file after you have cloned NodeBB.

Step 2: Install redis with Cloud9’s package manager

nada-nix install redis

Step 3: Run your redis server on port 16379 - port 6379 tends to be already used on Cloud 9. The “&” makes the command run in the background. You can always terminate the process later. $IP is a Cloud 9 system variable containing the global ip of your server instance.

redis-server --port 16379 --bind $IP &

Step 4: Find out your instance’s ip address so NodeBB can bind to it correctly. This is one of Cloud 9’s demands and seems to be the only way it will work. You can’t use $IP in your config.json either (which means you can’t enter $IP in the node app –setup).

echo $IP

Step 5: Install NodeBB and it’s dependencies:

npm install

Step 6: Run the nodebb setup utility:

node app --setup

URL of this installation should be set to ‘http://workspace_name-c9-username.c9.io‘, replacing workspace_name with your workspace name and username with your username. Note that as NodeBB is currently using unsecure http for loading jQuery you will find it much easier using http:// instead of https:// for your base url. Otherwise jQuery won’t load and NodeBB will break.

Port number isn’t so important - Cloud9 may force you to use port 80 anyway. Just set it to 80. If this is another port, like 4567, that is also fine.

Use a port number to access NodeBB? Again, this doesn’t seem to make a big difference. Set this to no. Either will work.

Host IP or address of your Redis instance: localhost (the output of the $IP Command is also acceptable)

IP or Hostname to bind to: Enter what your $IP value holds here found in step 4. It should look something like: 123.4.567.8

Host port of your Redis instance: 16379

Redis Password: Unless you have set one manually, Redis will be configured without a password. Leave this blank and press enter

First-time set-up will also require an Admin name, email address and password to be set.

And you’re good to go! Don’t use the Run button at the top if the IDE, it has been a little buggy for me. Besides, you’re better off using the command line anyway. Run:

node app

And then open http://workspace_name-c9-username.c9.io in your browser.

Troubleshooting

A common problem is that the database hasn’t been started. Make sure you have set Redis up correctly and ran

redis-server --port 16379 --bind $IP

Heroku

Note: Installations to Heroku require a local machine with some flavour of unix, as NodeBB does not run on Windows.

  1. Download and install Heroku Toolbelt for your operating system

  2. Log into your Heroku account: heroku login

  3. Verify your Heroku account by adding a credit card (at http://heroku.com/verify)

  4. Clone the repository: git clone -b v0.7.x https://github.com/NodeBB/NodeBB.git /path/to/repo/clone

  5. cd /path/to/repo/clone

  6. Install dependencies locally npm install --production

  7. Create the heroku app: heroku create

  8. Enable Redis To Go for your heroku account: heroku addons:create redistogo:nano

  9. Run the NodeBB setup script: node app --setup (information for your Heroku server and Redis to Go instance can be found in your account page)

    • Your server name is found in your Heroku app’s “settings” page, and looks something like adjective-noun-wxyz.herokuapp.com
    • Use any port number. It will be ignored.
    • Your redis server can be found as part of the redis url. For example, for the url: redis://redistogo:h28h3wgh37fns7@crestfish.redistogo.com:12345/
    • The server is fishyfish.redistogo.com
    • The port is 12345
    • The password is h28h3wgh37fns7
  10. Add the following three packages to the dependencies section of your package.json:

"dependencies": {
    ...
    "nodebb-plugin-dbsearch": "0.0.10",
    "redis": "~0.10.1",
    "connect-redis": "~2.0.0"
},
"devDependencies": {
  1. Create a Procfile for Heroku: echo "web: node loader.js --no-daemon" > Procfile
  2. Commit the Procfile:
git rm npm-shrinkwrap.json && git add -f Procfile config.json package.json && git commit -am "adding Procfile and configs for Heroku"
  1. Push to heroku: git push -u heroku v0.7.x:master * Ensure that a proper SSH key was added to your account, otherwise the push will not succeed!
  2. Initialise a single dyno: heroku ps:scale web=1
  3. Visit your app!

If these instructions are unclear or if you run into trouble, please let us know by filing an issue.

Keeping it up to date

If you wish to pull the latest changes from the git repository to your Heroku app:

  1. Navigate to your repository at /path/to/nodebb
  2. git pull
  3. npm install
  4. node app --upgrade
  5. git commit -am "upgrading to latest nodebb"
  6. git push

Nitrous.IO

The following are installation instructions for the Nitrous.IO <http://nitrous.io>.

Step 1: Create a new application in boxes with NodeJS :

https://www.nitrous.io/app#/boxes/new

Step 2: Open terminal / SSH to the application / Open IDE

Step 3: Get the files of NodeBB, unzip, delete master.zip and cd to the folder

wget https://github.com/NodeBB/NodeBB/archive/v0.7.x.zip && unzip NodeBB-v0.7.x.zip && rm NodeBB-v0.7.x.zip && cd NodeBB-v0.7.x

Step 4: NPM Install

npm install

Step 5: Install Redis

parts install redis

Step 6: Setup NodeBB

./nodebb setup

Leave everything as default but you can change yourself.

I recommend the port number to bind : 8080

Step 14: And the last one, start NodeBB

./nodebb start

And then open the “Preview URI” without port if you have put for port : 8080.

Note

You can expand the resources of the application : http://www.nitrous.io/app#/n2o/bonus.

Openshift PaaS

The following are installation instructions for the Openshift <http://openshift.com> PaaS. Before starting, you need to install Red Hat’s rhc command line at https://developers.openshift.com/en/managing-client-tools.html.

Step 1: Go to https://openshift.redhat.com/app/console/applications and then create an application.

Step 2: Scroll down and paste the following URL address in “Code Anything” field box. Then click ‘Next’. ` http://cartreflect-claytondev.rhcloud.com/github/icflorescu/openshift-cartridge-nodejs `

Step 3: Type nodebb in application name. If you want another name, you might want this instead: nodeb-(name). Replace (name) to whatever you like. Note: If it’s your first time, you will see a note saying you need to specify a namespace. Namespace can be anything ... as long you do not change application name.

Step 4: Scroll all the way down and click ‘Create Application’. Then you need to wait for it to finish creating your first NodeBB application. Note: Do not make any changes to your application, just leave them as it is. Otherwise do it at your own risk as NodeBB might will not work correctly.

Step 5: You will be asked if you want to code your application. Simply click ‘Not now, contiune’. Then you will be redirected to an application page. It will tell you that it is created without any errors and it is started.

Step 6: Click ‘see the list of cartridges you can add’. Scroll down and then past the following URL address to “Install your own cartridge” field box. Then click ‘Next’. You should see if you want to confirm. Click ‘Add Cartridge’. ` http://cartreflect-claytondev.rhcloud.com/reflect?github=smarterclayton/openshift-redis-cart `

Step 7: You should see the notice that it is installed without any errors. It also will tell you the default password. Save it somewhere, as you will need it later.

Step 9: Open terminal (or Git Bash) and paste the following command to access SSH. ` rhc app ssh -a nodebb `

Note: If you got an error that it does not exist or similar, you need to do the following command and then try again. ` rhc setup `

Step 9: Paste the following command. Then save the necessary information. ` echo $OPENSHIFT_NODEJS_IP && echo $REDIS_CLI `

In order: First line: NodeJS IP address - You should save it. Second line: Redis IP address -h - You should save it. Redis Port -p - You should save it. Redis Password -a - It was already explained in Step 7.

Note: If you’re installing NodeBB with Redis first time, you should wipe databases (or one of your choice). Paste the following code. ` redis-cli $REDIS_CLI ` then ` flushall ` or ` select db_number_of_your_choice flushdb `

Step 10: Exit SSH by pasting the following command. ` exit `

Note: You might have to type ‘exit’ once, and then again to exit SSH completely.

Step 11: Go back to https://openshift.redhat.com/app/console/applications and then click NodeBB application. Copy the URL address from “Scoure Code.” A similar scoure code URL address should be this: ssh://[code]@nodebb-[namespace].rhcloud.com/~/git/nodebb.git/

Step 12: Go back to terminal. Paste the following command and then paste the URL address. ` git clone ssh://[code]@nodebb-[namespace].rhcloud.com/~/git/nodebb.git/ `

Note: If it exists, check to make sure you do not have more than four files. If it is, delete it and rerun the command. Otherwise contiune to next step.

Note: This will create NodeBB folder on your computer, usually ~/users/[name]/NodeBB

Step 13: Then cd to NodeBB folder on your computer. And you will need to clone NodeBB from Github to your application by using this command. The default command git clone will not work with Openshift, unless you’re in SSH. ` cd nodebb && git remote add upstream -m master https://github.com/NodeBB/NodeBB.git `

Step 14: Then pull files from NodeBB’s repository. ` git pull -s recursive -X theirs upstream v0.7.x `

Step 15: Now you will need to commit and push files to your application’s repository. Replace message with your message. It will take a while to finish, though. ` git commit -a -m 'message' && git push `

Step 16: Access SSH again. ` rhc app ssh -a nodebb `

Step 17: First cd then start the installation of NodeBB using interactive installer. ` cd ~/app-root/repo && ./nodebb setup `

Note: Web installer (npm start) might will not work because... it’s Openshift.

Step 18: Follow what this step carefully!!!

URL used to access this NodeBB (http://localhost:4567) - Copy and paste your application’s URL address and then add port 8080 like so: http://nodeb-[namespace].rhcloud.com:8080

Please enter a NodeBB secret (code) - Just press enter.

Which database to use (redis) - Database of your choice, otherwise just press enter.

Host IP or address of your Redis instance (127.0.0.1) - Copy & paste Redis’ IP address found in step 9.

Host port of your Redis instance (6379) - Copy & paste: 16379 OR copy & paste Redis’ port found in step 9.

Password of your Redis database - Enter your Redis password found in step 7 or step 9.

Which database to use (0) - Just press enter, unless you perfer different database, go ahead.

Step 19: Now you will need to edit config.json NodeBB had created. Paste the following command. ` nano config.json `

Step 20: Add a line below “url” and then add the following. Repleace NodeJS IP Address to IP address of your application found in step 9. Then exit the editor using CTRL+X. ` "bind_address": "NodeJS IP Address", `

Step 21: Now start your NodeBB on Openshift! And you’re done! Then visit your website: http://nodebb-[namespace].rhcloud.com/ ` ./nodebb start `

Note

Starting, stopping, reloading, or restarting NodeBB now works on Openshift. Be sure you always do this before doing it. (Replace [string] to a valid string.)

    rhc app ssh -a nodebb
cd ~/app-root/repo
./nodebb [string]

Koding

Note: Installations to Koding requires a free account on Koding.com. (This guide has been changed to reflect the changes to Koding.com as of September 2014)

  1. Create an account or log in to Koding.com <http://koding.com>
  2. Click the Green Icon at the top that looks like >_
  3. You will see your VM with Off to the right in red letters, click this, to power on your VM
  4. Click it again when it says Ready.
  5. You should now be inside a terminal window. The installation instructions are close to Ubuntu’s, but vary slightly, as certain packages are already installed.
  6. Firstly, we need to make sure we’re up to date - sudo apt-get update && sudo apt-get upgrade
  7. Enter your password you used to sign up, if you signed up using Github or another 3rd party, you will need to set one in your Account Settings. Then come back.
  8. Now run the following sudo apt-get install python-software-properties python g++ make
  9. Now we install NodeBBs other dependencies - sudo apt-get install redis-server imagemagick
  10. Next, we clone NodeBB into a NodeBB folder - git clone -b v0.7.x https://github.com/NodeBB/NodeBB.git nodebb (Optional: Replace nodebb at the end if you want the folder to be a different name)
  11. Now enter the NodeBB folder - cd nodebb (unless you changed the foldername in the previous step, if you somehow forgot what you called it, run ls to see the name of the folder)
  12. Now we install all the dependencies of NodeBB - npm install (could take a minute or two)
  13. Set up nodebb using - ./nodebb setup
  14. The first setup question will ask for the domain name, this will vary, do not use localhost. Your domain name/Access URI is found on the left sidepanel by clicking the small icon to the right of your koding-vm-ID underneath VMS (it’s a circle with 3 dots inside).
  15. Complete the setup (defaults after the domain name are fine to accept, so press enter a few times until you get to “Create an Admin”
  16. Create an Admin Username and password etc, it will then create categories and other things that make NodeBB awesome.
  17. Now we can start NodeBB - ./nodebb start
  18. Open another tab in your browser of choice and navigate to http://{uniqueID}.{yourkodingusername}.kd.io:4567 (assuming you didn’t change the port number during setup)
  19. You will see a screen to continue to your page, click the link about half way down to continue to your site.

Congratulations, you’ve successfully installed NodeBB on Koding.com

If these instructions are unclear or if you run into trouble, please let us know by filing an issue. (Be sure to mention @a5mith in your issue, as I wrote the guide)

Some issues with running on Koding

As Koding is free, it does come with some nuances to a regular cloud host:

  1. Your VM will switch off after 60 minutes of inactivity. This doesn’t mean the website unfortunately, but your Terminal Window (You can bypass this by keeping the terminal window open and running ls before your VM shuts down, alternatively, pay for the service and it will remain on)
  2. It can be temperamental, sometimes you may receive “Your VM is unavailable, try again later”, you can try logging out and back in, refreshing your page, or filing an issue with their support team.
  3. Koding.com uses Ubuntu 14.04 to host your VM, so a basic knowledge of Ubuntu would always help.

Installing NodeBB with Docker

The following are step-by-step guides to help you get up and running on the cloud using popular the Docker platform. For your convenience, we currently offer both CentOS and Ubuntu Docker builds.

You can view our official builds on Docker Hub Registry. If your intereasting in contributing to our Dockerfiles, you can fork our repository on GitHub.

Примечание

If the Docker Build of your choice is not listed here, please feel free to request a guide on our community or even better yet, submit one here.

NodeBB & Redis Installation

Requirements

In order to use the NodeBB Docker builds, you will need to have Docker installed. You can find install instructions for your system at http://docs.docker.com/.

Stable/Development Builds

By default, the NodeBB Docker builds install the stable version of NodeBB. To install the development version of NodeBB, simply append dev to the commands -dev.

Usage

To get started with running NodeBB using Docker, you will want to run a redis instance.

docker run --name my-forum-redis -d -p 6379:6379 nodebb/docker:centos-redis
docker run --name my-forum-redis -d -p 6379:6379 nodebb/docker:ubuntu-redis

Next, launch the NodeBB instance, so it links with the just-launched Redis instance.

docker run --name my-forum-nodebb --link my-forum-redis:redis -p 80:80 -p 443:443 -p 4567:4567 -P -t -i nodebb/docker:centos
docker run --name my-forum-nodebb --link my-forum-redis:redis -p 80:80 -p 443:443 -p 4567:4567 -P -t -i nodebb/docker:ubuntu

You will be asked to configure your NodeBB instance, as no config file was found. Simply press enter for all settings except Redis hostname, which should be redis as it is linked using the –linked parameter to our Redis instance, and the administrator username, e-mail and password.

The default port of nodebb is 4567. Ports 80, and 443 have also been exposed for your convenience. You can keep the default nodebb port or change it.

NodeBB will launch the setup and automatically close. Next, simply start the instance again. It will this time find a config file and start as a daemon.

docker start my-forum-nodebb

Your NodeBB instance will be accessible on the port you selected during setup. Check docker ps for more details.

Backup/Restoring

Simply use the /data volume inside your Redis instance. See the official guide on making backups.

Development Updates

  • NodeBB & MongoDB - Currently in development

Настройка NodeBB

The NodeBB Config (config.json)

The majority of NodeBB’s configuration is handled by the Administrator Control Panel (ACP), although a handful of server-related options are defined in the configuration file (config.json) located at NodeBB’s root folder.

Some of these values are saved via the setup script:

  • url is the full web-accessible address that points to your NodeBB. If you don’t have a domain, an IP address will work fine (e.g. http://127.0.0.1:4567). Subfolder installations also define their folder here as well (e.g. http://127.0.0.1:4567/forum)
  • secret is a text string used to hash cookie sessions. If the secret is changed, all existing sessons will no longer validate and users will need to log in again.
  • database defines the primary database used by NodeBB. (e.g. redis or mongo) – for more information, see Configuring Databases
  • Both redis and mongo are hashes that contain database-related connection information, they contain some or all of the following:
    • host
    • port
    • username (MongoDB only)
    • password
    • database

The following values are optional, and override the defaults set by NodeBB:

  • port (Default: 4567) Specifies the port number that NodeBB will bind to. You can specify an array of ports and NodeBB will spawn port.length processes. If you use multiple ports you need to configure a load balancer to proxy requests to the different ports.

  • bcrypt_rounds (Default: 12) Specifies the number of rounds to hash a password. Slower machines may elect to reduce the number of rounds to speed up the login process, but you’d more likely want to increase the number of rounds at some point if computer processing power gets so fast that the default # of rounds isn’t high enough of a barrier to password cracking.

  • upload_path (Default: /public/uploads) Specifies the path, relative to the NodeBB root install, that uploaded files will be saved in.

  • jobsDisabled This can be added to disable jobs that are run on a certain interval. For example “jobsDisabled”:true will disable daily digest emails and notification pruning.

  • socketio A hash with socket.io settings :

    • transports (Default: ["polling", "websocket"]) Can be used to configure socket.io transports.
    • address (Default: "") Address of socket.io server can be empty

Configuring Databases

NodeBB has a Database Abstraction Layer (DBAL) that allows one to write drivers for their database of choice. Currently we have the following options:

MongoDB

If you’re afraid of running out of memory by using Redis, or want your forum to be more easily scalable, you can install NodeBB with MongoDB. This tutorial assumes you know how to SSH into your server and have root access.

These instructions are for Ubuntu. Adjust them accordingly for your distro.

Note: If you have to add sudo to any command, do so. No one is going to hold it against you ;)

Step 1: Install MongoDB

The latest and greatest MongoDB is required (or at least greater than the package manager). The instructions to install it can be found on the MongoDB manual).

Step 2: Install node.js

Like MongoDB, the latest and greatest node.js is required (or at least greater than the package manager), so I’m leaving this to the official wiki. The instructions to install can be found on Joyent.

Note: NPM is installed along with node.js, so there is no need to install it separately

Step 3: Install the Base Software Stack

Enter the following into the terminal to install the base software required to run NodeBB:

# apt-get install git build-essential imagemagick
Step 4: Clone the Repository

Enter the following into the terminal, replacing /path/to/nodebb/install/location to where you would like NodeBB to be installed.

$ cd /path/to/nodebb/install/location
$ git clone git://github.com/NodeBB/NodeBB.git nodebb
Step 5: Install The Required NodeBB Dependencies

Go into the newly created nodebb directory and install the required dependencies by entering the following.

$ cd nodebb
$ npm install
Step 6: Adding a New Database With Users

To go into the MongoDB command line, type:

$ mongo

To add a new database called nodebb, type:

> use nodebb

To add a user to access the nodebb database, type:

For MongoDB 2.6.x

> db.createUser( { user: "nodebb", pwd: "<Enter in a secure password>", roles: [ "readWrite" ] } )

Note: NodeBB requires MongoDB 2.6.0 or higher. The role readWrite provides read or write any collection within a specific database to user.

Step 7: Configure MongoDB

Modify /etc/mongodb.conf.

# nano /etc/mongodb.conf

To enable authentication, uncomment auth = true. Restart MongoDB.

# service mongodb restart
Step 8: Configuring NodeBB

Make sure you are in your NodeBB root folder. If not, just type:

$ cd /path/to/nodebb

To setup the app, type:

$ node app --setup
  • Change the hostname to your domain name.
  • Accept the defaults by pressing enter until it asks you what database you want to use. Type mongo in that field.
  • Accept the default port, unless you changed it in the previous steps.
  • Change your username to nodebb, unless you set it to another username.
  • Enter in the password you made in step 5.
  • Change the database to nodebb, unless you named it something else.

Continue with the installation, following the instructions the installer provides you.

Step 9: Starting the App

To start the app, run:

$ ./nodebb start

Now visit yourdomainorip.com:4567 and your NodeBB installation should be running.

NodeBB can also be started with helper programs, such as supervisor or forever. You can also use nginx as a reverse proxy).

Advanced Settings

The mongodb nodejs driver has a default connection pool size of 5, if you need to increase this just add a poolSize setting into your config.json file under the mongo block.

LevelDB

Follow the installation instructions for your particular OS but feel free to omit the Redis installation.

After cloning NodeBB, ensure that you run:

npm install levelup leveldown

Finally, set up a directory to store your LevelDB database, for example:

mkdir /var/level/

Run the NodeBB install, select level when it prompts you for your database. If you created the folder as above, you can leave the rest of the questions as default.

Примечание

If you would like to write your own database driver for NodeBB, please visit our community forum and we can point you in the right direction.

Running a Secondary Database

Предупреждение

This option is experimental and should not be used on a production environment.

Both databases must be flushed before beginning - there isn’t a mechanism yet that detects an existing installation on one database but not another. Until fail-safe’s such as these are implemented this option is hidden under the --advanced setup flag.

node app --setup --advanced

Consult the other database guides for instructions on how to set up each specific database. Once you select a secondary database’s modules, there’s no turning back - until somebody writes an exporter/importer.

Currently this setup is being tested with Redis as the primary store (sets, lists, and sorted sets, because Redis is super fast with these), and Mongo as the hash store (post and user data, because ideally we wouldn’t want this in RAM).

Configuring Web Server / Proxies

Here a few options that you can use to proxy your NodeBB forum.

Configuring nginx as a proxy

NodeBB by default runs on port 4567, meaning that builds are usually accessed using a port number in addition to their hostname:

http://example.org:4567

In order to allow NodeBB to be served without a port, nginx can be set up to proxy all requests to a particular hostname (or subdomain) to an upstream NodeBB build running on any port.

Requirements
  • NGINX version v1.3.13 or greater
Configuration

NGINX-served sites are contained in a server block. This block of options goes in a specific place based on how nginx was installed and configured:

  • /path/to/nginx/sites-available/* – files here must be aliased to ../sites-enabled
  • /path/to/nginx/conf.d/*.conf – filenames must end in .conf
  • /path/to/nginx/httpd.conf – if all else fails

Below is the basic nginx configuration for a NodeBB build running on port 4567:

server {
    listen 80;

    server_name forum.example.org;

    location / {
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_set_header X-NginX-Proxy true;

        proxy_pass http://127.0.0.1:4567/;
        proxy_redirect off;

        # Socket.IO Support
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
    }
}

Below is another nginx configuration for a NodeBB that has port:[“4567”,”4568”] in config.json.

server {
    listen 80;

    server_name forum.example.org;

    location / {
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_set_header X-NginX-Proxy true;

        proxy_pass http://io_nodes;
        proxy_redirect off;

        # Socket.IO Support
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
    }
}

upstream io_nodes {
    ip_hash;
    server 127.0.0.1:4567;
    server 127.0.0.1:4568;
}

Below is an nginx configuration which uses SSL.

### redirects http requests to https
server {
    listen 80;
    server_name forum.example.org;

    return 301 https://forum.example.org$request_uri;
}

### the https server
server {
    # listen on ssl, deliver with speedy if possible
    listen 443 ssl spdy;

    server_name forum.example.org;

    ssl on;

    # change this path!
    ssl_certificate /path/to/cert/bundle.crt;

    # change this path!
    ssl_certificate_key /path/to/cert/forum.example.org.key;

    # enables all versions of TLS, but not SSLv2 or 3 which are weak and now deprecated.
    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;

    # disables all weak ciphers
    ssl_ciphers 'AES128+EECDH:AES128+EDH';

    ssl_prefer_server_ciphers on;

    location / {
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_set_header X-NginX-Proxy true;

        proxy_pass http://127.0.0.1:4567/;
        proxy_redirect off;

        # Socket.IO Support
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
    }
}
Notes
  • nginx must be on version 1.4.x to properly support websockets. Debian/Ubuntu use 1.2, although it will work there will be a reduction in functionality.
  • The proxy_pass IP should be 127.0.0.1 if your NodeBB is hosted on the same physical server as your nginx server. Update the port to match your NodeBB, if necessary.
  • This config sets up your nginx server to listen to requests for forum.example.org. It doesn’t magically route the internet to it, though, so you also have to update your DNS server to send requests for forum.example.org to the machine with nginx on it!

Configuring apache as a proxy

Note: This requires Apache v2.4.x or greater. If your version of Apache is lower, please see :doc:`Apache v2.2.x Instructions <proxies/apache2.2>`

Enable the necessary modules
  1. sudo a2enmod proxy
  2. sudo a2enmod proxy_http
  3. sudo a2enmod proxy_wstunnel
Add the config to Apache

The next step is adding the configuration to your virtualhost.conf file, typically located in /etc/apache2/sites-available/. The below configuration assumes you’ve used 4567 (default) port for NobeBB installation. It also assumes you have the bind address set to 127.0.0.1.

ProxyRequests off

<Proxy *>
    Order deny,allow
    Allow from all
</Proxy>
ProxyPass /socket.io/1/websocket ws://127.0.0.1:4567/socket.io/1/websocket
ProxyPassReverse /socket.io/1/websocket ws://127.0.0.1:4567/socket.io/1/websocket

ProxyPass /socket.io/ http://127.0.0.1:4567/socket.io/
ProxyPassReverse /socket.io/ http://127.0.0.1:4567/socket.io/

ProxyPass / http://127.0.0.1:4567/
ProxyPassReverse / http://127.0.0.1:4567/

The last thing you need to be sure of is that the config.json in the NodeBB folder defines the node.js port outside of the url:

Example nodebb/config.json
{
    "url": "http://www.yoursite.com",
    "port": "4567",
    "secret": "55sb254c-62e3-4e23-9407-8655147562763",
    "database": "redis",
    "redis": {
        "host": "127.0.0.1",
        "port": "6379",
        "password": "",
        "database": "0"
    }
}

Change the domain and dont use the secret in the example above.

Configuring Apache v2.2.x as a reverse proxy to NodeBB

Prerequisites:

You need to manually compile and add the module mod_proxy_wstunnel to the Apache 2.2 branch. If you’re running Ubuntu (prior to 14.04) or Debian, you’re likely on the 2.2 branch of code.

Please use this guide to backport the mod_proxy_wstunnel module into the 2.2 code base of Apache:

http://www.amoss.me.uk/2013/06/apache-2-2-websocket-proxying-ubuntu-mod_proxy_wstunnel

*Note: On ubuntu, if you’re missing the ./configure file, you need to first run ./buildconf. After this is complete, you will then be able to use ./configure.*

Configuring Varnish Cache

To be sure Varnish will work properly with NodeBB check that your configuration /etc/varnish/default.vcl is optimized for websockets.

backend nodebb {
  .host = "127.0.0.1"; # your nodebb host
  .port = "4567"; # your nodebb port
}

sub vcl_recv {

  # Pipe websocket connections directly to Node.js
  if (req.http.Upgrade ~ "(?i)websocket") {
    set req.backend = nodebb;
    return (pipe);
  }

  # NodeBB
  if (req.http.host == "forum.yourwebsite.com") { # change this to match your host
    if (req.url ~ "^/socket.io/") {
        set req.backend = nodebb;
        return (pipe); # return pass seems not working for websockets
    }
    return (pass); # don't cache
  }

}

sub vcl_pipe {
  # Need to copy the upgrade header
  if (req.http.upgrade) {
    set bereq.http.upgrade = req.http.upgrade;
  }
}

Запуск NodeBB

Running NodeBB

The preferred way to start and stop NodeBB is by invoking its executable:

  • ./nodebb start Starts the NodeBB server
  • ./nodebb stop Stops the NodeBB server
  • Alternatively, you may use npm start and npm stop to do the same

The methods listed below are alternatives to starting NodeBB via the executable.

Upstart

Later version of Ubuntu may utilise Upstart to manage processes at boot. Upstart also handles restarts of scripts if/when they crash.

You can use Upstart to start/stop/restart your NodeBB.

Note: Prior to NodeBB v0.7.0, Upstart processes would not track the proper pid, meaning there was no way to stop the NodeBB process. NodeBB v0.7.0 includes some changes that allow Upstart to control NodeBB more effectively.

You can utilise this Upstart configuration as a template to manage your NodeBB:

start on startup
stop on runlevel [016]
respawn
setuid someuser
setgid someuser
script
        cd /path/to/nodebb
        node loader.js --no-silent --no-daemon
end script

From there, you can start stop and restart NodeBB as the root user: start nodebb, stop nodebb, restart nodebb, assuming nodebb.conf is the name of the Upstart config file.

Simple Node.js Process

To start NodeBB, run it with node (some distributions use the executable nodejs, please adjust accordingly):

$ cd /path/to/nodebb/install
$ node app

However, bear in mind that crashes will cause the NodeBB process to halt, bringing down your forum. Consider some of the more reliable options, below:

Supervisor Process

Using the supervisor package, you can have NodeBB restart itself if it crashes:

$ npm install -g supervisor
$ supervisor app

As supervisor by default continues to pipe output to stdout, it is best suited to development builds.

Forever Daemon

Another way to keep NodeBB up is to use the forever package via the command line interface, which can monitor NodeBB and re-launch it if necessary:

$ npm install -g forever
$ forever start app.js

Grunt Development

We can utilize grunt to launch NodeBB and re-compile assets when files are changed. Start up speed is increased because we don’t compile assets that weren’t modified.

Installing Grunt

$ npm install -g grunt-cli

Run grunt to start up NodeBB and watch for code changes.

$ grunt

Обновление NodeBB

Upgrading NodeBB

NodeBB’s periodic releases are located in the Releases. These releases contain what is usually considered the most bug-free code, and is designed to be used on production-level instances of NodeBB.

You can utilise git to install a specific version of NodeBB, and upgrade periodically as new releases are made.

To obtain the latest fixes and features, you can also git clone the latest version directly from the repository (master branch), although its stability cannot be guaranteed. Core developers will attempt to ensure that every commit results in a working client, even if individual features may not be 100% complete.

*As always*, the NodeBB team is not responsible for any misadventures, loss of data, data corruption, or any other bad things that may arise due to a botched upgrade - so please don’t forget to back up before beginning!

Upgrade Path

NodeBB’s upgrade path is designed so that upgrading between versions is straightforward. NodeBB will provide upgrade compatibility (via the --upgrade flag) between the latest version of a lower branch and the latest version of the higher branch. For example, if v0.2.2 is the latest version in the v0.2.x branch, you can switch to the v0.3.x branch and suffer no ill effects. Upgrading from v0.2.0 to v0.3.x is not supported, and NodeBB will warn you when attempting to upgrade that you are not upgrading cleanly.

Upgrading between patch revisions

e.g. v0.1.0 to v0.1.1

Patch revisions contain bugfixes and other minor changes. Updating to the latest version of code for your specific version branch is all that is usually required.

Execute steps 1 through 3.

Upgrading between minor revisions

e.g. v0.1.3 to v0.2.0

Minor revisions contain new features or substantial changes that are still backwards compatible. They may also contain dependent packages that require upgrading, and other features may be deprecated (but would ideally still be supported).

Execute steps 1 through 4.

Upgrade Steps

Note: After upgrading between revisions (i.e. v0.0.4 to v0.0.5), it may be necessary to run the following upgrade steps to ensure that any data schema changes are properly upgraded as well:

1. Shut down your forum

While it is possible to upgrade NodeBB while it is running, it is definitely not recommended, particularly if it is an active forum:

$ cd /path/to/nodebb
$ ./nodebb stop
2. Back up your data

Примечание

This section is incomplete, please take care to back up your files properly!

Backing up Redis

As with all upgrades, the first step is to back up your data! Nobody likes database corruption/misplacement.

All of the textual data stored in NodeBB is found in a .rdb file. On typical installs of Redis, the main database is found at /var/lib/redis/dump.rdb.

Store this file somewhere safe.

Backing up MongoDB

To run a backup of your complete MongoDB you can simply run

mongodump

which will create a directory structure that can be restored with the mongorestore command.

It is recommended that you first shut down your database. On Debian / Ubuntu it’s likely to be: sudo service mongodb stop

Backing up LevelDB

As LevelDB is simply a collection of flat files, just copy the database over to a safe location, ex.

cp -r /path/to/db /path/to/backups

Store this file somewhere safe.

Avatars

Uploaded images (avatars) are stored in /public/uploads. Feel free to back up this folder too:

cd /path/to/nodebb/public
tar -czf ~/nodebb_assets.tar.gz ./uploads
3. Grab the latest and greatest code

Navigate to your NodeBB: $ cd /path/to/nodebb.

If you are upgrading from a lower branch to a higher branch, switch branches as necessary. *Make sure you are completely up-to-date on your current branch!*.

For example, if upgrading from v0.3.2 to v0.4.3:

$ git fetch    # Grab the latest code from the NodeBB Repository
$ git checkout v0.4.x    # Type this as-is! Not v0.4.2 or v0.4.3, but "v0.4.x"!
$ git merge origin/v0.4.x

If not upgrading between branches, just run the following command:

$ git pull

This should retrieve the latest (and greatest) version of NodeBB from the repository.

Alternatively, download and extract the latest versioned copy of the code from the Releases Page. Overwrite any files as necessary. This method is not supported.

4. Run the NodeBB upgrade script

This script will install any missing dependencies, upgrade any plugins or themes (if an upgrade is available), and migrate the database if necessary.

$ ./nodebb upgrade

Note: ./nodebb upgrade is only available after v0.3.0. If you are running an earlier version, run these instead:

  • npm install
  • ls -d node_modules/nodebb* | xargs -n1 basename | xargs npm update
  • node app --upgrade
6. Start up NodeBB & Test!

You should now be running the latest version of NodeBB.

Администрирование NodeBB

Administrative Functions

Примечание

These docs are out of date. If you are interested in updating these (preferably with screenshots) let us know on the community forum because we are planning on a design overhaul of the ACP soon.

To view the admin panel (if you are an admin): http://your_nodebb_domain.com/admin

Top Menu (all can be easily reached by other means)
  • NodeBB ACP (Administrator Control Panel: this view) * http://your_nodebb_domain.com/admin/index (see Home below)
  • Forum * http://your_nodebb_domain.com (your main forum)
  • Home * http://your_nodebb_domain.com/admin/index (see Home below)
  • Settings * http://your_nodebb_domain.com/admin/settings (see Settings below)
Side Menu: NodeBB
  • Home * http://your_nodebb_domain.com/admin/index * Links all go to nodebb.com homepage

    • NOTE: should all the links go to same place?
    • Message reminder of what version this is and to check for updates (See Upgrading NodeBB) * NOTE: would a link to where the latest stable version is help?
    • Active Users * lists number users per page-path (?) * NOTE: not clear exactly what the paths mean or how to visit that path
  • Categories * http://your_nodebb_domain.com/admin/categories * Filters: Active, Disabled, Unit Tests * List of Categories:

    • Icon, Name, Desc, Action: Disable
    • Actions: Save, Add New
  • Users * http://your_nodebb_domain.com/admin/users * Filters: Latest Users, Top Posters, Most Reputation, Action: Search * List of Users:

    • Icon, Link: Name, Reputation(star), Number Posts(pencil), Action: Ban
    • Action: Load More
  • Groups * http://your_nodebb_domain.com/admin/groups

    • List of Groups
    • Name, Desc, Icon
    • Action: Delete Group * NOTE: What exactly can Groups be set up to do, besides Admin?
  • Topics * http://your_nodebb_domain.com/admin/topics * List of Topics

    • Name [link to topic], Posted When and By, Number posts (Topic+Replies), Thread Actions: Pin(pushpin), Lock(lock), Delete(trashcan)
    • Action: Load More Topics

    • Topic [from List of Topics link]

    • Normal View of Topic+Reply Posts but with: * Link, Edit, Delete Actions all enabled for each Post * Thread Tools:

      • Pin, Lock, Move, Delete
  • Themes (See Theming NodeBB) * http://your_nodebb_domain.com/admin/themes * List of (Custom | Bootswatch) Themes

    • Actions: Use, Preview
    • Action: Revert (to base)
  • Plugins (See Writing Plugins for NodeBB) * http://your_nodebb_domain.com/admin/plugins * List of Plugins

    • Action: De/activate
    • Info on making plugins
  • Settings * http://your_nodebb_domain.com/admin/settings

    • General Settings * (textbox) Site Title * (textbox) Site Description * (textbox) Site Keywords * (textbox) Imgur Client ID

      • NOTE: How does this function?
      • (textbox) Maximum User Image Size
    • Privilege Thresholds (Use privilege thresholds to manage how much reputation a user must gain to receive moderator access.) * (textbox) Manage Thread * (textbox) Moderate Users * (textbox) Create Pinned Topics

    • Email Settings * (textbox) Email Address (The following email address refers to the email that the recipient will see in the “From” and “Reply To” fields.) * (textbox) SMTP Server Host (Default: 127.0.0.1) * (textbox) SMTP Server Port

    • User Settings * (textbox) Minimum Username Length * (textbox) Maximum Username Length * (textbox) Minimum Password Length

    • Post Settings * (textbox) Post Delay * (textbox) Minimum Title Length * (textbox) Minimum Post Length * (checkbox) Use Outgoing Links Warning Page

    • Action: Save

  • Redis * http://your_nodebb_domain.com/admin/redis * Redis data storage stats

  • Logger * http://your_nodebb_domain.com/admin/logger * (checkbox) Enable HTTP logging * (checkbox) Enable socket.io event logging * (textbox) Path to log file

  • MOTD (Message of the Day) * http://your_nodebb_domain.com/admin/motd * (textarea) You can enter either full HTML or Markdown text. * (checkbox) Show the Message of the Day

Side Menu: Social Authentication (See Enabling Social Network Logins)

  • Twitter
  • http://your_nodebb_domain.com/admin/twitter
  • Facebook
  • http://your_nodebb_domain.com/admin/facebook
  • Google+
  • http://your_nodebb_domain.com/admin/gplus

Side Menu: Plugins (Shows installed plugins)

Side Menu: Unit Tests (Will run qunit tests)

Social Network SSOs

NodeBB supports integration for Facebook, Twitter, and Google through third party plugins:

  • npm install nodebb-plugin-sso-facebook
  • npm install nodebb-plugin-sso-twitter
  • npm install nodebb-plugin-sso-google

Other SSO vendors are available, such as GitHub. Please check the plugin directory for a list of all SSO vendors.

After installing and activating them, they require an API key in order to function:

Facebook

Register an application via the Facebook Developers page. A credit card or mobile phone number may be required in order to create a Developer account.

Create a new application, and obtain an Application Key and Application Secret:

http://i.imgur.com/hfy0eVo.png

Ensure that “Website with Facebook Login” is checked, and that the URL to your NodeBB instance is specified in the “Site URL” box. Add that site’s domain to the “App Domains” field.

Paste this key and secret into the appropriate boxes in the NodeBB Administration Panel (accessible via /admin on your NodeBB install)

Twitter

Register an application at the Twitter Developers page. Create a new Application, and obtain the Access Token and Secret:

http://i.imgur.com/ksrHkgN.png

Important: While setting up your application, be sure to specify a Callback URL. It does not have to correspond to your installation, it just cannot be blank.

Paste this token and secret into the appropriate boxes in the NodeBB Administration Panel (accessible via /admin on your NodeBB install)

Google

Register an application at the Google API Console, and obtain a Client ID and Secret.

http://i.imgur.com/xutDs1R.png

Paste this ID and secret into the appropriate boxes in the NodeBB Administration Panel (accessible via /admin on your NodeBB install)

Image Hosting APIs

Enabling Imgur Image Uploads

To enable post image attachments, first create an imgur app from :

https://api.imgur.com/oauth2/addclient

You can use : “Anonymous usage without user authorization”

After that you will get a “Client ID”.

Then install nodebb-plugin-imgur:

npm install nodebb-plugin-imgur

Activate the plugin from the control panel and restart NodeBB.

You should see a Imgur menu item in the control panel. Paste the Client ID to the “Imgur Client ID” in the plugin page. Save and you should be able to upload images by dragging them into the composer window.

Uploading to Amazon S3

Примечание

No documentation for this yet! See the plugin thread for more information.

Масштабирование NodeBB

Scaling NodeBB

When it comes to maintaining many concurrent connections or high view rates, there are certain procedures that can be followed in order to streamline NodeBB.

This article attempts to outline the various strategies that can be employed by those finding that NodeBB is not running as fast as it should under full load.

Utilise clustering

By default, NodeBB will run on one process, and certain calls may take longer than others, resulting in a lag or queue for the same resources. To combat this, you can instruct NodeBB to run on multiple processes by adding the port property into your config.json:

{
    "port": ["4567", "4568", "4569"]  // will start three processes
}

Keep in mind you need to start nodebb with node loader.js or ./nodebb start so that 3 workers can be spawned. Using node app.js will only use the first port in the array.

A proxy server like Nginx is required in order to load balance requests between all of the servers. Add an upstream block to your config:

upstream io_nodes {
    ip_hash;
    server 127.0.0.1:4567;
    server 127.0.0.1:4568;
    server 127.0.0.1:4569;
}

... and alter the proxy_pass value to read: proxy_pass http://io_nodes;

Use a proxy server to serve static assets

Nginx is exceedingly good at serving static resources (e.g. javascript, css, images, etc). By allowing Nginx to take over the task of serving this to the end user, the NodeBB process(es) will be left to handle only the API calls, which substantially lowers the amount of work for NodeBB (and increases your throughput).

Your Nginx config will need to be modified add the following location blocks:

location @nodebb {
    proxy_pass http://127.0.0.1:4567;
}

location ~ ^/(images|language|sounds|templates|uploads|vendor|src\/modules|nodebb\.min\.js|stylesheet\.css|admin\.css) {
    root /path/to/nodebb/public/;
    try_files $uri $uri/ @nodebb;
}

location / {
    proxy_pass http://127.0.0.1:4567;
}

Furthermore, you can instruct Nginx to serve these assets compressed:

gzip            on;
gzip_min_length 1000;
gzip_proxied    off;
gzip_types      text/plain application/xml application/x-javascript text/css application/json;

Sample Nginx configuration with all of the above applied

upstream io_nodes {
    ip_hash;
    server 127.0.0.1:4567;
    server 127.0.0.1:4568;
    server 127.0.0.1:4569;
}
server {
    listen 80;

    server_name community.nodebb.org;

    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header Host $http_host;
    proxy_set_header X-NginX-Proxy true;
    proxy_redirect off;

    # Socket.io Support
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";

    gzip            on;
    gzip_min_length 1000;
    gzip_proxied    off;
    gzip_types      text/plain application/xml application/x-javascript text/css application/json;

    location @nodebb {
        proxy_pass http://io_nodes;
    }

    location ~ ^/(images|language|sounds|templates|uploads|vendor|src\/modules|nodebb\.min\.js|stylesheet\.css|admin\.css) {
        root /path/to/nodebb/public/;
        try_files $uri $uri/ @nodebb;
    }

    location / {
        proxy_pass http://io_nodes;
    }
}

Участие в разработке NodeBB

NodeBB Style Guide

For the most part, NodeBB follows the Google Javascript Style Guide.

Code Formatting

Примечание

The existing codebase as of July 2013 does not adhere to this style guide 100%. If you see instances where the style guide is not adhered to, feel free to restyle and send off a pull request.

Indentation & Bracing

NodeBB uses tabbed indentation. Bracing should follow the One True Brace Style:

if (condition) {
    // code here ...
} else {
    // otherwise ...
}

Put conditionals and statements on separate lines and wrap with curly braces even if it’s just one line:

if (leTired) {
    haveANap();
}

Errors

Most callbacks return an error as the first parameter. Handle this error first before processing further.

someFunction(parameters, function(err, data) {
    if(err) {
       return callback(err); // or handle error
    }
    // proceed as usual
});

Variables

Variables should always be prefaced with the var keyword:

var foo = 'bar';

Multiple declarations are to be included in the same var statement:

var foo = 'bar',
    bar = 'baz';

Semicolons

Use semicolons if at all possible

Nomenclature

CamelCase if at all possible:

functionNamesLikeThis, variableNamesLikeThis, ClassNamesLikeThis, EnumNamesLikeThis, methodNamesLikeThis, CONSTANT_VALUES_LIKE_THIS, foo.namespaceNamesLikeThis.bar, and filenameslikethis.js.

Core Modules

Примечание

This section is under construction. Have a look at the modules folder for more information, located at:

public/src/modules

Alerts

The alert module is a toaster notification that can be called via the following syntax:

app.alert({
    title: 'Success!',
    message: 'Here\'s an example of an alert!',
    location: 'left-bottom',
    timeout: 2500,
    type: 'success',
    image: 'https://i.imgur.com/dJBzcGT.jpg'
});

The above code will result in this notification (default styling):

https://i.imgur.com/jRD5GAI.png

To style this, have a look at the vanilla theme’s modules/alert.less and templates/alert.tpl.

Parameters:

  1. title - string, which can be a language string as well. Some core language strings that you can use here include: [[global:alert.success]] and [[global:alert.error]]
  2. message - string, which can be a language string as well.
  3. location (optional) - right-top (default), left-top, right-bottom, left-bottom
  4. timeout (optional) - integer in milliseconds, default is permanent until closed.
  5. type - error, success, info, warning/notify
  6. image (optional) - string, URL to image.
  7. closefn (optional) - function. This is called when the user closes the alert via the (X) button.
  8. clickfn (optional) - function. This is called when the user clicks on the alert.

Система Плагинов

Writing Plugins for NodeBB

So you want to write a plugin for NodeBB, that’s fantastic! There are a couple of things you need to know before starting that will help you out.

Like WordPress, NodeBB’s plugins are built on top of a hook system in NodeBB. This system exposes parts of NodeBB to plugin creators in a controlled way, and allows them to alter content while it passes through, or execute certain behaviours when triggered.

See the full list of hooks for more information.

Filters and Actions

There are two types of hooks: filters and actions.

Filters act on content, and can be useful if you want to alter certain pieces of content as it passes through NodeBB. For example, a filter may be used to alter posts so that any occurrences of “apple” gets changed to “orange”. Likewise, filters may be used to beautify content (i.e. code filters), or remove offensive words (profanity filters).

Actions are executed at certain points of NodeBB, and are useful if you’d like to do something after a certain trigger. For example, an action hook can be used to notify an admin if a certain user has posted. Other uses include analytics recording, or automatic welcome posts on new user registration.

When you are writing your plugin, make sure a hook exists where you’d like something to happen. If a hook isn’t present, file an issue and we’ll include it in the next version of NodeBB.

Configuration

Each plugin package contains a configuration file called plugin.json. Here is a sample:

{
    "url": "Absolute URL to your plugin or a Github repository",
    "library": "./my-plugin.js",
    "staticDirs": {
        "images": "public/images"
    },
    "less": [
        "assets/style.less"
    ],
    "hooks": [
        { "hook": "filter:post.save", "method": "filter" },
        { "hook": "action:post.save", "method": "emailme" }
    ],
    "languages": "path/to/languages",
    "nbbpm": {
        "compatibility": "^0.7.0"
    }
}

The library property is a relative path to the library in your package. It is automatically loaded by NodeBB (if the plugin is activated).

The staticDirs property is an object hash that maps out paths (relative to your plugin’s root) to a directory that NodeBB will expose to the public at the route /plugins/{YOUR-PLUGIN-ID}.

  • e.g. The staticDirs hash in the sample configuration maps /path/to/your/plugin/public/images to /plugins/my-plugin/images

The less property contains an array of paths (relative to your plugin’s directory), that will be precompiled into the CSS served by NodeBB.

The hooks property is an array containing objects that tell NodeBB which hooks are used by your plugin, and what method in your library to invoke when that hook is called. Each object contains the following properties (those with a * are required):

  • hook, the name of the NodeBB hook
  • method, the method called in your plugin
  • priority, the relative priority of the method when it is eventually called (default: 10)

The languages property is optional, which allows you to set up your own internationalization for your plugin (or theme). Set up a similar directory structure as core, for example: language/en_GB/myplugin.json.

The nbbpm property is an object containing NodeBB package manager info.

  • compatibility is a semver specifying the NodeBB version that this plugin is compatible with.

Writing the plugin library

The core of your plugin is your library file, which gets automatically included by NodeBB if your plugin is activated.

Each method you write into your library takes a certain number of arguments, depending on how it is called:

  • Filters send a single argument through to your method, while asynchronous methods can also accept a callback.
  • Actions send a number of arguments (the exact number depends how the hook is implemented). These arguments are listed in the list of hooks.

Example library method

If we were to write method that listened for the action:post.save hook, we’d add the following line to the hooks portion of our plugin.json file:

{ "hook": "action:post.save", "method": "myMethod" }

Our library would be written like so:

var MyPlugin = {
        myMethod: function(postData) {
            // do something with postData here
        }
    };

Using NodeBB libraries to enhance your plugin

Occasionally, you may need to use NodeBB’s libraries. For example, to verify that a user exists, you would need to call the exists method in the User class. To allow your plugin to access these NodeBB classes, use module.parent.require:

var User = module.parent.require('./user');
User.exists('foobar', function(err, exists) {
    // ...
});

Installing the plugin

In almost all cases, your plugin should be published in npm, and your package’s name should be prefixed “nodebb-plugin-”. This will allow users to install plugins directly into their instances by running npm install.

When installed via npm, your plugin must be prefixed with “nodebb-plugin-”, or else it will not be found by NodeBB.

As of v0.0.5, “installing” a plugin by placing it in the /plugins folder is still supported, but keep in mind that the package id and its folder name must match exactly, or else NodeBB will not be able to load the plugin. This feature may be deprecated in later versions of NodeBB.

Testing

Run NodeBB in development mode:

./nodebb dev

This will expose the plugin debug logs, allowing you to see if your plugin is loaded, and its hooks registered. Activate your plugin from the administration panel, and test it out.

Disabling Plugins

You can disable plugins from the ACP, but if your forum is crashing due to a broken plugin you can reset all plugins by executing

./nodebb reset plugins

Alternatively, you can disable one plugin by running

./nodebb reset plugin="nodebb-plugin-im-broken"

To disable plugins or a single plugin without the nodebb script, you can use the following node calls:

node app.js --reset --plugins
node app.js --reset --plugin="nodebb-plugin-im-broken"

Available Hooks

The following is a list of all hooks present in NodeBB. This list is intended to guide developers who are looking to write plugins for NodeBB. For more information, please consult Writing Plugins for NodeBB.

There are two types of hooks, filters, and actions. Filters take an input (provided as a single argument), parse it in some way, and return the changed value. Actions take multiple inputs, and execute actions based on the inputs received. Actions do not return anything.

Important: This list is by no means exhaustive. Hooks are added on an as-needed basis (or if we can see a potential use case ahead of time), and all requests to add new hooks to NodeBB should be sent to us via the issue tracker.

As of 2014-10-08 we have moved the list of hooks into our wiki page. Please consult the list here.

Settings Framework

If you want to make your plugin customizable you may use the Settings Framework NodeBB offers.

Server-Side Access

First you need some default settings, just create a new object for this:

var defaultSettings = {
        booleans: {
            someBool: true,
            moreBools: [false, false, true]
        },
        strings: {
            someString: 'hello world',
            multiLineString: 'some\nlong\ntext',
            arrayOfStrings: ['some\nlong\ntexts', 'and another one']
        },
        numbers: {
            multiArrayDimensions: [[42,42],[21,21]],
            multiArrayDimensions2: [[42,42],[]],
            justSomeNumbers: [],
            oneNumber: 3,
            anotherNumber: 2
        },
        someKeys: ['C+S+#13'] // Ctrl+Shift+Enter
    };

Now you can use the server-side settings-module to access the saved settings like this:

var Settings = module.parent.require('./settings');
var mySettings = new Settings('myPlugin', '0.1', defaultSettings, function() {
    // the settings are ready and can accessed.
    console.log(mySettings === this); // true
    console.log(this.get('strings.someString') === mySettings.get().strings.someString); // true
});

The second parameter should change at least every time the structure of default settings changes. Because of this it’s recommended to use your plugins version.

To use the settings client-side you need to create a WebSocket that delivers the result of mySettings.get().

The mySettings-object will cache the settings, so be sure to use methods like mySettings.sync(callback) when the settings got changed from somewhere else and mySettings.persist(callback) when you finished mySettings.set(key, value) calls.

You need to create a socket-listener like following to allow the admin to initiate a synchronization with the settings stored within database:

var SocketAdmin = module.parent.require('./socket.io/admin');
SocketAdmin.settings.syncMyPlugin = function() {
    mySettings.sync();
};

If you want to add a reset-functionality you need to create another socket-listener:

SocketAdmin.settings.getMyPluginDefaults = function (socket, data, callback) {
    callback(null, mySettings.createDefaultWrapper());
};

The methods of the mySettings object you probably want to use:

  • constructor()
  • sync([callback])
    Reloads the settings from database, overrides local changes.
  • persist([callback])
    Saves the local changes within database.
  • get([key])
    Returns the setting(s) identified by given key. If no key is provided the whole settings-object gets returned. If no such setting is saved the default value gets returned.
  • set([key, ]value)
    Sets the setting of given key to given value. Remember that it’s just a local change, you need to call persist in order to save the changes.
  • reset([callback])
    Persists the default settings.
  • getWrapper()
    Returns the local object as it would get saved within database.
  • createWrapper(version, settings)
    Creates an object like it would get saved within database containing given information and settings.
  • createDefaultWrapper()
    Creates an object like it would get saved within database containing the default settings.

Client-Side Access

The next step is making the settings available to the admin.

You need to use the hooks filter:admin.header.build (to display a link to your page within ACP) and action:app.load (to create the needed route).

Within your page you can access the client-side Settings API via

require(['settings'], function (settings) {
    var wrapper = $('#my_form_id');
    // [1]
    settings.sync('myPlugin', wrapper);
    // [2]
});

To make a button with the id save actually save the settings you can add the following at [2]:

$('#save').click(function(event) {
    event.preventDefault();
    settings.persist('myPlugin', wrapper, function(){
        socket.emit('admin.settings.syncMyPlugin');
    });
});

As said before the server-side settings-object caches the settings, so we emit a WebSocket to notify the server to synchronize the settings after they got persisted.

To use a reset-button you can add the following at [2]:

$('#reset').click(function(event) {
    event.preventDefault();
    socket.emit('admin.settings.getMyPluginDefaults', null, function (err, data) {
        settings.set('myPlugin', data, wrapper, function(){
            socket.emit('admin.settings.syncMyPlugin');
        });
    });
});

There you go, the basic structure is done. Now you need to add the form-fields.

Each field needs an attribute data-key to reference its position within the settings. The Framework does support any fields whose jQuery-object provides the value via the val() method.

The plugin to use for a field gets determined by its data-type, type or tag-name in this order.

Additionally the following plugins are registered by default:
  • array (types: div, array)
    An Array of any other fields. Uses the object within data-attributes to define the array-elements. Uses data-new to define the value of new created elements.
  • key (types: key)
    A field to input keyboard-combinations.
  • checkbox, number, select, textarea
    Handle appropriate fields.

A full list of all attributes that may influence the behavior of the default Framework:

  • data-key: the key to save/load the value within configuration-object
  • data-type: highest priority type-definition to determine what kind of element it is or which plugin to associate
  • type: normal priority type-definition
  • data-empty: if false or 0 then values that are assumed as empty turn into null. data-empty of arrays affect their child-elements
  • data-trim: if not false or 0 then values will get trimmed as defined by the elements type
  • data-split: if set and the element doesn’t belong to any plugin, it’s value will get split and joined by its value into the field
  • array-elements:
    • data-split: separator (HTML allowed) between the elements, defaults to ', '
    • data-new: value to insert into new created elements
    • data-attributes: an object to set the attributes of the child HTML-elements. tagName as special key will set the tag-name of the child HTML-elements
  • key-fields:
    • data-trim: if false or 0 then the value will get saved as string else as object providing following properties: ctrl, alt, shift, meta, code, char
    • data-split: separator between different modifiers and the key-code of the value that gets saved (only takes effect if trimming)
    • data-short: if not false or 0 then modifier-keys get saved as first uppercase character (only takes effect if trimming)
  • select:
    • data-options: an array of objects containing text and value attributes.

The methods of the settings module:

  • registerPlugin(plugin[, types])
    Registers the given plugin and associates it to the given types if any, otherwise the plugins default types will get used.
  • get()
    Returns the saved object.
  • set(hash, settings[, wrapper[, callback[, notify]]])
    Refills the fields with given settings and persists them. hash Identifies your plugins settings. settings The object to save in database (settings-wrapper if you use server-side Settings Framework). wrapper (default: ‘form’) The DOM-Element that contains all fields to fill. callback (default: null) Gets called when done. notify (default: true) Whether to display saved- and fail-notifications.
  • sync(hash[, wrapper[, callback]])
    Resets the settings to saved ones and refills the fields.
  • persist(hash[, wrapper[, callback[, notify]]])
    Reads the settings from given wrapper (default: ‘form’) and saves them within database.

For Settings 2.0 support the methods load and save are still available but not recommended.

Client-Side Example Template

An example template-file to use the same settings we already used server-side:

<h1>My Plugin</h1>
<hr />

<form id="my_form_id">
    <div class="row">
        <p>
            <h2>Settings</h2>
            A boolean: <input type="checkbox" data-key="booleans.someBool"></input><br>
            An array of checkboxes that are selected by default:
            <div data-key="booleans.moreBools" data-attributes='{"data-type":"checkbox"}' data-new='true'></div><br>

            A simple input-field of any common type: <input type="password" data-key="strings.someString"></input><br>
            A simple textarea: <textarea data-key="strings.multiLineString"></textarea><br>
            Array of textareas:
            <div data-key="strings.arrayOfStrings" data-attributes='{"data-type":"textarea"}' data-new='Hello Kitty, ahem... World!'></div><br>

            2D-Array of numbers that persist even when empty (but not empty rows):
            <div data-key="numbers.multiArrayDimensions" data-split="<br>"
                data-attributes='{"data-type":"array","data-attributes":{"type":"number"}}' data-new='[42,21]'></div><br>
            Same with persisting empty rows, but not empty numbers, if no row is given null will get saved:
            <div data-key="numbers.multiArrayDimensions2" data-split="<br>" data-empty="false"
                data-attributes='{"data-type":"array","data-empty":true,"data-attributes":{"type":"number","data-empty":false}}' data-new='[42,21]'></div><br>
            Array of numbers (new: 42, step: 21):
            <div data-key="numbers.justSomeNumbers" data-attributes='{"data-type":"number","step":21}' data-new='42'></div><br>
            Select with dynamic options:
            <select data-key="numbers.oneNumber" data-options='[{"value":"2","text":"2"},{"value":"3","text":"3"}]'></select><br>
            Select that loads faster:
            <select data-key="numbers.anotherNumber"><br>
                <option value="2">2</option>
                <option value="3">3</option>
            </select>

            Array of Key-shortcuts (new: Ctrl+Shift+7):
            <div data-key="someKeys" data-attributes='{"data-type":"key"}' data-new='Ctrl+Shift+#55'></div><br>
        </p>
    </div>
    <button class="btn btn-lg btn-warning" id="reset">Reset</button>
    <button class="btn btn-lg btn-primary" id="save">Save</button>
</form>

<script>
    require(['settings'], function (settings) {
        var wrapper = $('#my_form_id');
        // [1]
        settings.sync('myPlugin', wrapper);
        $('#save').click(function(event) {
            event.preventDefault();
            settings.persist('myPlugin', wrapper, function(){
                socket.emit('admin.settings.syncMyPlugin');
            });
        });
        $('#reset').click(function(event) {
            event.preventDefault();
            socket.emit('admin.settings.getMyPluginDefaults', null, function (err, data) {
                settings.set('myPlugin', data, wrapper, function(){
                    socket.emit('admin.settings.syncMyPlugin');
                });
            });
        });
      });
</script>

Custom Settings-Elements

If you want do define your own element-structure you can create a plugin for the Settings Framework.

This allows you to use a whole object like a single field which - besides comfort in using multiple similar objects - allows you to use them within arrays.

A plugin is basically an object that contains at least an attribute types that contains an array of strings that associate DOM-elements with your plugin.

You can add a plugin at [1] using the method settings.registerPlugin.

To customize the way the associated fields get interpreted you may add the following methods to your plugin-object:

All given elements are instances of JQuery.

All methods get called within Settings-scope.

  • use()
    Gets called when the plugin gets registered.
  • [HTML-Element|JQuery] create(type, tagName, data)
    Gets called when a new element should get created (eg. by expansion of an array).
  • destruct(element)
    Gets called when the given element got removed from DOM (eg. by array-splice).
  • init(element)
    Gets called when an element should get initialized (eg. after creation).
  • [value] get(element, trim, empty)
    Gets called whenever the value of the given element is requested. trim Whether the result should get trimmed. empty Whether considered as empty values should get saved too.
  • set(element, value, trim)
    Gets called whenever the value of the given element should be set to given one. trim Whether the value is assumed as trimmed.

For further impression take a look at the default plugins.

You should also take a look at the helper-functions within Settings in order to create your own plugins. There are a few methods that take response to call the methods of other plugins when fittingly.

Система Виджетов

Writing Widgets for NodeBB

See the original blog post for a high level overview and screenshots of the widget system.

Embedding HTML and JavaScript

You don’t need to be a developer to figure this out. Head over to the Themes control panel and click on the Widgets tab. Create a new HTML widget by dragging and dropping the widget onto whatever template you want.

Copy and paste HTML or JavaScript into the widget and hit save - you’re done!

You can optionally give your widget a container by dragging and dropping from the containers section onto your selected widget.

If you’re looking for some sample scripts, head over to our plugins section and look for any topic labelled nodebb-script-xyz. Don’t forget to submit your scripts and ideas as well!

Creating Widgets

You can define widgets in both plugins and themes. If you’re building a plugin which simply delivers a widget (or collection of widgets), we strongly suggest you follow the nodebb-widget-xyz nomenclature instead when publishing.

Registering your widget

Listen to this hook to register your widget:

"hook": "filter:widgets.getWidgets", "method": "defineWidgets", "callbacked": true

Pass this back in the array:

Content defines the form that is displayed to customize your widget in the admin panel.

Listening to your widget

NodeBB core will call your widget on the appropriate page load by way of the hooks system. The hook will be named after your widget’s namespace (see previous example) - like so: filter:widget.render:widget_namespace

This will pass in an object with the following useful properties:

  • obj.area - will have location, template, url
  • obj.data - will have your admin-defined data; in the example from the previous section you will be exposed an obj.data.myKey

Defining Widget Areas in Themes

A Widget Area is characterized by a template and a location. Themes can share widgets if they define the same Widget Areas. If an admin switches themes, widgets that were previously defined in a Widget Area incompatible with the new theme are saved.

Listen to this hook to register your Widget Area:

"hook": "filter:widgets.getAreas", "method": "defineWidgetAreas", "callbacked": true

Pass this back in the array:

{
        name: "Category Sidebar",
        template: "category.tpl",
        location: "sidebar"
}

And that’s all. You can define as many Widget Areas in your theme as you wish. If you’re still stuck, have a look at this commit which upgraded the Cerulean theme to use the widget system.

Создание тем

Creating a new NodeBB Theme

NodeBB is built on Twitter Bootstrap, which makes theming incredibly simple.

Packaging for NodeBB

NodeBB expects any installed themes to be installed via npm. Each individual theme is an npm package, and users can install themes through the command line, ex.:

npm install nodebb-theme-modern-ui

The theme’s folder must contain at least two files for it to be a valid theme:

  1. theme.json
  2. theme.less

theme.less is where your theme’s styles will reside. NodeBB expects LESS to be present in this file, and will precompile it down to CSS on-demand. For more information regarding LESS, take a look at the project homepage.

Note: A suggested organization for theme.less is to @import multiple smaller files instead of placing all of the styles in the main theme.less file.

Configuration

The theme configuration file is a simple JSON string containing all appropriate meta data regarding the theme. Please take note of the following properties:

  • id: A unique id for a theme (e.g. “my-theme”)
  • name: A user-friendly name for the theme (e.g. “My Theme”)
  • description: A one/two line description about the theme (e.g. “This is the theme I made for my personal NodeBB”)
  • screenshot: A filename (in the same folder) that is a preview image (ideally, 370x250, or an aspect ratio of 1.48:1)
  • url: A fully qualified URL linking back to the theme’s homepage/project
  • templates: (Optional) A system path (relative to your plugin’s root directory) to the folder containing template files. If not specified, NodeBB will search for the “templates” directory, and then simply fall back to using vanilla’s template files.
  • baseTheme: (Optional) If undefined, will use nodebb-theme-vanilla (our current base theme) as a default for missing template files. See the Child Themes section for more details.

Child Themes

CSS / LESS

If your theme is based off of another theme, simply modify your LESS files to point to the other theme as a base, ex for topics.less:

As topic.less from the theme nodebb-theme-vanilla was imported, those styles are automatically incorporated into your theme.

Templates

You do not need to redefine all templates for your theme. If the template file does not exist in your current theme, NodeBB will inherit templates from the baseTheme that you have defined in your theme.json (or if undefined, it will inherit from nodebb-theme-vanilla‘s templates).

Configuration

If you depend on another theme, make sure that your theme specifically states this in its package.json. For example, for the above theme, as we depend on nodebb-theme-vanilla, we would explicitly state this by adding a new section into the package.json file:

"peerDependencies": {
    "nodebb-theme-vanilla": "~0.0.1"
}

If your theme is dependent on a theme that is not nodebb-theme-vanilla, you should set the baseTheme configuration in your theme.json to the appropriate theme.

Rendering Engine

How it works

Every page has an associated API call, Template file, and Language File.

For example, if you navigate to /topic/351/nodebb-wiki, the application will load three resources. The API return /api/topic/351/nodebb-wiki and the template, in this example, “topic.tpl”, and the appropriate language file “topic.json”*.

Just prepend api/ to the URL’s path name to discover the JSON return. Any value in that return can be utilized in your template.

*A page’s name corresponds to the template and language’s filename (ex. http://domain.com/topic/xyz correlates to topic.tpl). Sometimes this is not the case - ex. /user/xyz loads account.tpl. Have a look at the custom_mapping section in public/templates/config.json for more details.

Templating Basics

Using the API return as your guide, you can utilize any of those values in your template/logic. Using the above API call as an example, for anything in the root level of the return you can do something like:

{topic_name}

To access values in objects:

{privileges.read}

And finally you can loop through arrays and create blocks like so:

<!-- BEGIN posts -->
{posts.content}
<!-- END posts -->

The above will create X copies of the above block, for each item in the posts array.

Templating Logic

NodeBB’s templating system implements some basic logic. Using the same API call as above for our example. You can write IF conditionals like so:

<!-- IF unreplied -->
This thread is unreplied!
<!-- ENDIF unreplied -->

Another example:

<!-- IF !disableSocialButtons -->
<button>Share on Facebook</button>
<!-- ELSE -->
Sharing has been disabled.
<!-- ENDIF !disableSocialButtons -->

We can check for the length of an array like so:

<!-- IF posts.length -->
There be some posts
<!-- ENDIF posts.length -->

While looping through an array, we can check if our current index is the @first or @last like so:

<!-- BEGIN posts -->
  <!-- IF @first -->
    <h1>Main Author: {posts.username}</h1>
  <!-- ENDIF @first -->
  {posts.content}
  <!-- IF @last -->
    End of posts. Click here to scroll to the top.
  <!-- ENDIF @last -->
<!-- END posts -->

For more advanced documentation, have a look at the templates.js repository

Exposing template variables to client-side JavaScript

There are two ways of letting our JS know about data from the server-side, apart from WebSockets (TODO: will be covered in a different article).

Via jQuery.get

If we require data from a different page we can make a $.get call to any other API call. For example, if we wanted to know more about a specific user we could make a call like so:

$.get(RELATIVE_PATH + '/api/user/psychobunny', {}, function(user) {
    console.log(user)
});

See this API call in action: http://community.nodebb.org/api/user/psychobunny

Via Template Variables

In topic.tpl for example, we can add a hidden input like so:

<input type="hidden" template-variable="pageCount" value="{pageCount}" />

The template system will immediately parse all of these and expose them via the following method:

ajaxify.variables.get('pageCount');

This is the ideal method of letting JS know about important variables within the template.

Internationalization

The template engine interfaces with the internationalization system as well. We can embed variables into language strings. Let’s use this API call as well as this language file as an example. We can now do something like the following:

[[register:help.username_restrictions, {minimumUsernameLength}, {maximumUsernameLength}]]

Which will translate this string:

A unique username between %1 and %2 characters

to

A unique username between 2 and 16 characters

Advanced Topics

Dynamically requiring and rendering a template file from client-side JavaScript

The template engine lazy loads templates on an as-needed basis and caches them. If your code requires a template or partial on-demand then you can :

ajaxify.loadTemplate('myTemplate', function(myTemplate) {
        var html = templates.parse(myTemplate, myData);
});

You can also access the invidual blocks inside each template, which is handy for doing things like (for example) rendering a new post’s <li> and dynamically sticking it in an already loaded <ul>

Some stuff here...
<!-- BEGIN posts -->
We just want to pull this block only.
<!-- END posts -->
... some stuff here
ajaxify.loadTemplate('myTemplate', function(myTemplate) {
        var block = templates.getBlock(myTemplate, 'posts');
        var html = templates.parse(block, myData);
});
Rendering templates on server-side Node.js

The templating system hooks into Express just like most other templating frameworks. Just use either app.render or res.render to parse the appropriate template.

res.render('myTemplate', myData);
app.render('myTemplate', myData, function(err, parsedTemplate) {
        console.log(parsedTemplate);
});

Ресурсы для разработчика

Developer’s Resources

Примечание

This section is under construction.

Core

Themes

Widgets

Помощь проекту

Helping out the NodeBB Project

NodeBB is an open source project, and will forever remain free. Here’s a number of ways you can help us, even if you aren’t a programmer.

  • Like and share our content on Facebook
  • Follow us on Twitter and perhaps tweet #NodeBB is most awesome forum software @NodeBB
  • Update our wiki! ;) We need everything from development/design tutorials to user friendly how-to guides.
  • Tell everybody about NodeBB, including your grandma and her cats.
  • Submit a pull request, or two, or three..
  • Build a new theme
  • Write a plugin
  • Keep the link back to us on the footer of your own NodeBB :)
  • Blog about us! Give the gift of SEO juice this Christmas
  • Help Translate NodeBB - It’s a really simple translation tool and you don’t need to know how to code.
  • Join our community and give us a hard time about bugs and missing features

Translating NodeBB to another language

NodeBB uses Transifex, which is a user friendly visual tool which allows any individual to translate text into a language of their choice. You don’t need to be a programmer to do this, so what are you waiting for? Join the translation team now :)

Writing Documentation

These docs were written using Sphinx and published using rtfd.org.

You can edit these docs directly on GitHub, or by clicking on “View page source” on the top right of any page.

If you wish, you can clone the repository and compile the documentation yourself. Check out the Getting Started section for more info on how to accomplish the latter.

Documentation are auto-compiled and pushed to rtfd.org after every commit.

Диагностика / Помощь

Need Help?

Frequently Asked Questions

If you experience difficulties setting up a NodeBB instance, perhaps one of the following may help.

How do I start/stop/restart NodeBB?

You can call the ./nodebb executable to start and stop NodeBB:

$ ./nodebb
    Welcome to NodeBB
    Usage: ./nodebb {start|stop|reload|restart|log|setup|reset|upgrade|dev|watch}

    start    Start the NodeBB server
    stop     Stops the NodeBB server
    reload   Restarts NodeBB
    restart  Restarts NodeBB
    log      Opens the logging interface (useful for debugging)
    setup    Runs the NodeBB setup script
    reset    Disables all plugins, restores the default theme.
    upgrade  Run NodeBB upgrade scripts, ensure packages are up-to-date
    dev      Start NodeBB in interactive development mode
    watch    Start NodeBB in development mode and watch for changes
How do I upgrade my NodeBB?

Please consult Upgrading NodeBB

I upgraded NodeBB and now X isn’t working properly!

Please consult Upgrading NodeBB

I installed an incompatible plugin, and now my forum won’t start!

If you know which plugin caused problems, disable it by running: ./nodebb reset plugin="nodebb-plugin-pluginName"

Otherwise, disable all plugins by running: ./nodebb reset plugins

Is it possible to install NodeBB via FTP?

It is possible to transfer the files to your remote server using FTP, but you do require shell access to the server in order to actually “start” NodeBB. Here is a handy guide for installing NodeBB on DigitalOcean

I’m getting an “npm ERR!” error

For the most part, errors involving npm are due to Node.js being outdated. If you see an error similar to this one while running npm install:

npm ERR! Unsupported
npm ERR! Not compatible with your version of node/npm: connect@2.7.11

You’ll need to update your Node.js version to 0.8 or higher.

To do this on Ubuntu:

# add-apt-repository ppa:chris-lea/node.js
# apt-get update && apt-get dist-upgrade -y

If successful, running the following command should show a version higher than 0.8

# apt-cache policy nodejs
URLs on my NodeBB (or emails) still have the port number in them!

If you are using nginx or Apache as a reverse proxy, you don’t need the port to be shown. Simply run ./nodebb setup and specify the base URL without a port number.

Alternatively, edit the config.json file using your favourite text editor and change use_port to false.

The “Recently Logged In IPs” section only shows 127.0.0.1

NodeBBs running behind a proxy may have difficulties determining the original IP address that requests come from. It is important that the proxy server provides the referral IP header.

In nginx, ensure that the following line is present in your server block:

proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

In addition, ensure that the use_port option is set to false in your NodeBB’s config.json

Submit Bugs on our Issue Tracker

Before reporting bugs, please ensure that the issue has not already been filed on our tracker, or has already been resolved on our support forum. If it has not been filed, feel free to create an account on GitHub and create a new issue.

Ask the NodeBB Community

Having trouble installing NodeBB? Or did something break? Don’t hesitate to join our forum and ask for help. Hopefully one day you’ll be able to help others too :)