官术网_书友最值得收藏!

Writing your first app

Now that you have everything installed and confirmed that it's all working, you can write your first quick app that will use both Node and MongoDB. This will prove that your environment is good to go, and you're ready to get started. In addition, it will give you a brief taste of the world of Node and MongoDB development! Don't worry if a lot of the following is confusing or just doesn't make sense to you—it will all be made clear throughout the rest of the book!

To begin with, we need to create a folder for our application where this application's specific code will reside, as follows:

$ mkdir testapp
$ cd testapp

Creating the sample application

The testapp folder that we just created will be the root of our sample Node application. Even though it's not necessary, it's important and also a best practice that we should create the package.json file for our Node app, which will hold the necessary data regarding the application such as its version, name, description and development, and runtime dependencies. This can be done by issuing the following command from the testapp folder root:

$ npm init

This command will follow up by asking you a few questions such as the name and version number of your newly created application. It is not necessary that you fill in all the details in one go, and you can skip the steps by pressing Enter and the default values will be entered, which you may update later.

Getting the dependent modules in place

Before we start to write any Node.js code, we need to get our dependencies in place by using npm. Since this is a basic app, we will be using it to test our Node.js connectivity with the MongoDB server. So, the only dependent module that we need is the native MongoDB client for Node.js. We can easily install that by executing the following command:

$ npm install mongodb --save

After npm installs the MongoDB driver, you can list the contents of the directory and notice that a new folder was created, node_modules. This is where, surprisingly enough, all Node modules are stored whenever you install them from npm. Inside the node_modules folder should be a single folder named mongodb. Also, you will notice that the package.json file of our sample application will be updated by this new dependency entry.

主站蜘蛛池模板: 甘谷县| 福清市| 阳原县| 阜平县| 长寿区| 永年县| 邢台县| 五大连池市| 玛沁县| 若羌县| 阿拉尔市| 佛教| 万安县| 凯里市| 潮安县| 保靖县| 莱州市| 丰台区| 仙游县| 临泉县| 洮南市| 湘阴县| 唐河县| 东阿县| 武清区| 油尖旺区| 东山县| 罗山县| 肃宁县| 隆德县| 扶绥县| 含山县| 正蓝旗| 喀喇| 监利县| 普洱| 军事| 阳朔县| 古交市| 重庆市| 衡东县|