Home Web Front-end JS Tutorial Nodejs tutorial environment installation and operation_node.js

Nodejs tutorial environment installation and operation_node.js

May 16, 2016 pm 04:30 PM
nodejs Environment installation run

Let nodeJS run

The first step is of course to install the nodeJS environment. Now it is faster to install nodeJS on windows. Just download it directly:

http://www.nodejs.org/download/

Download here as needed. After the download is completed, just go to the next step. After that, we will have a nodeJS environment

The second step, in order to facilitate our subsequent operations, we directly created a folder blog on the D drive

Then open the windows command line tool, enter the d drive, enter:

Copy code The code is as follows:
express -e blog

Then there may be dependent packages inside. We need to enter the blog directory to install (the installation configuration is provided by package.json):

Copy code The code is as follows:
npm install

In this way, our dependency package has been downloaded. The dependency package, java package file, and .net bll file should be the same concept

At this time, our program is ready to run:

Copy code The code is as follows:
node app

Copy code The code is as follows:
D:blog>node appExpress server listening on port 3000

When you open the browser at this time, there will be a reaction:

Here we are using express (a popular nodeJS web development framework) and the ejs template engine

File structure

The initialization file directory structure is as follows:

app.js is the entry file

package.json is a module dependency file. When we use npm install, it will download related packages from the Internet based on its configuration

node_modules is the downloaded module file (package.json)

public stores static resource files

routes stores routing files

views stores related view template files

In this way, our basic directory structure comes out. Let’s briefly talk about the node_modules directory

node_modules/ejs

As we just said, downloaded modules are stored here. To put it bluntly, it is a collection of js files

Copy code The code is as follows:

var parse = exports.parse = function(str, options){
  var options = options || {}
    , open = options.open || exports.open || '<%'
    , close = options.close || exports.close || '%>'
    , filename = options.filename
    , compileDebug = options.compileDebug !== false
    , buf = "";

  buf = 'var buf = [];';
  if (false !== options._with) buf = 'nwith (locals || {}) { (function(){ ';
  buf = 'n buf.push('';

  var lineno = 1;

  var consumeEOL = false;
  for (var i = 0, len = str.length; i < len; i) {
    var stri = str[i];
    if (str.slice(i, open.length i) == open) {
      i = open.length
 
      var prefix, postfix, line = (compileDebug ? '__stack.lineno=' : '') lineno;
      switch (str[i]) {
        case '=':
          prefix = "', escape((" line ', ';
          postfix = ")), '";
          i;
          break;
        case '-':
          prefix = "', (" line ', ';
          postfix = "), '";
          i;
          break;
        default:
          prefix = "');" line ';';
          postfix = "; buf.push('";
      }

      var end = str.indexOf(close, i)
        , js = str.substring(i, end)
        , start = i
        , include = null
        , n = 0;

      if ('-' == js[js.length-1]){
        js = js.substring(0, js.length - 2);
        consumeEOL = true;
      }

      if (0 == js.trim().indexOf('include')) {
        var name = js.trim().slice(7).trim();
        if (!filename) throw new Error('filename option is required for includes');
        var path = resolveInclude(name, filename);
        include = read(path, 'utf8');
        include = exports.parse(include, { filename: path, _with: false, open: open, close: close, compileDebug: compileDebug });
        buf = "' (function(){" include "})() '";
        js = '';
      }

      while (~(n = js.indexOf("n", n))) n , lineno ;
      if (js.substr(0, 1) == ':') js = filtered(js);
      if (js) {
        if (js.lastIndexOf('//') > js.lastIndexOf('n')) js = 'n';
        buf = prefix;
        buf = js;
        buf = postfix;
      }
      i = end - start close.length - 1;

} else if (stri == "\") {
buf = "\\";
} else if (stri == "'") {
buf = "\'";
} else if (stri == "r") {
// ignore
} else if (stri == "n") {
If (consumeEOL) {
​​​​ consumeEOL = false;
} else {
buf = "\n";
         lineno ;
}
} else {
       buf = stri;
}
}

if (false !== options._with) buf = "'); })();n} nreturn buf.join('');";
else buf = "');nreturn buf.join('');";
Return buf;
};

For example, we used the ejs template and express module here, and then we curiously walked into the ejs program to see what the difference was

After opening ejs.js, let’s take a look at some code: We are familiar with this code. It has the same idea as underscore’s template engine code, which parses the template into a string

Then convert it into a function through the eval or new Function method, and pass in your own data object for easy analysis

As for the specific workflow, we don’t know yet. We can only study it later. Okay, let’s move on to other modules now

app.js

As the entry file, app.js plays a pivotal role:

Copy code The code is as follows:

/**
 * Module dependencies.
 */

var express = require('express');
var routes = require('./routes');
var user = require('./routes/user');
var http = require('http');
var path = require('path');

var app = express();

// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));

// development only
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}

app.get('/', routes.index);
app.get('/users', user.list);

http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' app.get('port'));
});

We load express and http modules through the require() command, and will load template files such as index user in the routes directory

app.set('port', process.env.PORT || 3000) is to set the port at startup

app.set('views', __dirname '/views') is to set the path to store the template file, where __dirname is a global variable, which stores the directory where the current script is located. We can view it like this:

Copy code The code is as follows:

console.log(__dirname);//Add the following code to index.js
/**
D:blog>node app
Express server li
D:blogroutes
*/

As for how this __dirname was obtained, we don’t need to pay attention for the time being

app.set('view engine', 'ejs') sets the template engine to ejs

app.use(express.favicon()) is to set the icon. If you want to modify it, just go to the images file under public

app.use(express.logger('dev')); express relies on connect, so the built-in middleware will output some logs

app.use(express.json()); is used to parse the request body, where the string will be dynamically converted into a json object

app.use(express.methodOverride()); connect has built-in middleware to process post requests and can disguise http methods such as put

app.use(app.router); Call router parsing rules

app.use(express.static(path.join(__dirname, 'public'))); connect built-in middleware, set public in the root directory to store static files

Copy code The code is as follows:

if ('development' == app.get('env')) {
app.use(express.errorHandler());
}

This sentence means that error messages should be output during development

Copy code The code is as follows:

app.get('/', routes.index);
app.get('/users', user.list);

These two sentences are specific processing files at the time of access. For example, when accessing directly here, the default access is routes.index

Then the template data is actually parsed internally:

Copy code The code is as follows:

exports.index = function (req, res) {
console.log(__dirname);
res.render('index', { title: 'Express' });
};

Finally, the above code will be called to create an http server and listen to port 3000. After success, it can be accessed on the web page

Routing

We used this method to build routing earlier

Copy code The code is as follows:
app.get('/', routes.index);

The above code can be replaced by this code (written in the app)

Copy code The code is as follows:

app.get('/', function (req, res) {
res.render('index', { title: 'Express' });
});

This code means that when accessing the homepage, the ejs template engine is called to render the index.ejs template file

Now make some modifications. The above code implements the routing function, but we cannot put the routing related code into the app. If there are too many routes, the app will become bloated, so we put the relevant configuration into the index

So delete the relevant routing functions in the app and add the code at the end of the app:

Copy code The code is as follows:
routes(app);

Then modify index.js

Copy code The code is as follows:

module.exports = function(app) {
app.get('/', function (req, res) {
res.render('index', { title: 'Express' });
});
};

It’s not clear yet how this code is organized, so I won’t pay attention to it. We will take a look at it later

Routing Rules

Express encapsulates a variety of http requests, we generally use get/post two types

Copy code The code is as follows:

app.get();
app.post();

The first parameter is the request path, the second parameter is the callback function, or the two parameters are request and response

Then, there are the following rules for req (request)

req.query handles get requests and obtains get request parameters

req.params handles get or post requests in the form of /:xxx

req.body processes post requests and obtains post request bodies

req.params handles get and post requests, but the search priority is req.params->req.body->req.query

Path rules also support regular expressions, we will talk about the details later...

Add routing rules

When we visit a non-existent link:

Because there is no routing rule for /y, and it does not mention files under public, so it is 404

Now we add relevant routes in index.js:

Copy code The code is as follows:

module.exports = function (app) {
app.get('/', function (req, res) {
res.render('index', { title: 'Express' });
});
app.get('/y', function (req, res) {
Res.send('Ye Xiaochai');
});
};

My page is garbled here:

The reason is that after downloading, my file is encoded in gbk. We just need to change it to utf-8. We will not care about the template engine. Let’s go to the next section

Registration function

Here we follow the original blogger to create a simple registration function. Here we use mongo db as the database, and we will improve the functions in sequence later

Create a new register route and create a new register template for it, so let’s get started

① Create a new route in index

Copy code The code is as follows:

app.get('/register', function (req, res) {
res.render('index', { title: 'Registration page' });
});

Copy code The code is as follows:

module.exports = function (app) {
app.get('/', function (req, res) {
res.render('index', { title: 'Express' });
});

app.get('/y', function (req, res) {
Res.send('Ye Xiaochai');
});

app.get('/register', function (req, res) {
res.render('register', { title: 'Registration page' });

});


Copy code The code is as follows:




<%= title %>



<%= title %>



                       
Username:

          
Password:

                                                                                                                                




In this way, our page is formed:

The basic program is now available, we now need database support, so we need to install the mongoDB environment

MongoDB

MongoDB is a type of NoSQL based on distributed file storage. It is written in C. The data structure supported by MongoDB is loose, similar to json. We know that json can support any type, so it can create very complex structures

Copy code The code is as follows:
{
id: 1,
name: 'Ye Xiaochai',
frinds: [
{ id: 2, name: 'Su Huan Zhen' },
{ id: 3, name: 'One page book' }
]
}

Install MongoDB

First go to http://www.mongodb.org/downloads to download the installation file, then copy the file to the D drive and rename it mongodb, and then create a new blog folder in it


Then open the command line tool and switch the directory to bin, enter:

Copy code The code is as follows:
mongod -dbpath d:mongodbblog
Set the blog folder as the project directory and start the database. For convenience in the future, we can write a command and click to start the database:

Copy code The code is as follows:
d:mongodbbinmongod.exe -dbpath d:mongodbblog

Link MongoDB

After the database is installed successfully, our program still needs the relevant "driver" program to link to the database. Of course, we must download the package at this time...

Open package.json and add a new line in dependencies

Copy code The code is as follows:

{
"name": "application-name",
"version": "0.0.1",
"private": true,
"scripts": {
"start": "node app.js"
},
"dependencies": {
"express": "3.4.8",
"ejs": "*",
"mongodb": "*"
}
}

Then run npm install to download the new dependency package. Now you have the driver related to mongoDB. To connect to databases such as mysql, you need other dependency packages

At this time, create the setting.js file in the root directory and save the database connection information

Copy code The code is as follows:

module.exports = {
cookieSecret: 'myblog',
db: 'blog',
host: 'localhost'
};

db is the database name, host is the database address, cookieSecret is used for cookie encryption and has nothing to do with the database

Next, create a new models folder in the root directory, and create a new db.js under the models folder

Copy code The code is as follows:

var settings = require('../settings'),
Db = require('mongodb').Db,
Connection = require('mongodb').Connection,
Server = require('mongodb').Server;
module.exports = new Db(settings.db, new Server(settings.host, Connection.DEFAULT_PORT), {safe: true});

Copy code The code is as follows:
new Db(settings.db, new Server(settings.host, Connection .DEFAULT_PORT), { safe: true });

Set the database name, database address and database port to create a database instance, and export the instance through module.exports, so that the database can be read and written through require

In order to successfully write to the database, the server-side program needs to process the post information, so we create a new user.js in the models folder

Copy code The code is as follows:

var mongodb = require('./db');

function User(user) {
this.name = user.name;
this.password = user.password;
};

module.exports = User;

//Storage user information
User.prototype.save = function (callback) {
//User documents to be stored in the database
var user = {
name: this.name,
Password: this.password
};
//Open database
mongodb.open(function (err, db) {
If (err) {
Return callback(err); //Error, return err information
}
//Read users collection
db.collection('users', function (err, collection) {
If (err) {
          mongodb.close();
           return callback(err); //Error, return err information
}
//Insert user data into users collection
      collection.insert(user, {
        safe: true
}, function (err, user) {
          mongodb.close();
If (err) {
              return callback(err); //Error, return err information
}
​​​​ callback(null, user[0]); //Success! err is null and returns the stored user document
});
});
});
};

Copy code The code is as follows:

//Read user information
User.get = function(name, callback) {
//Open database
mongodb.open(function (err, db) {
If (err) {
Return callback(err);//Error, return err information
}
//Read users collection
db.collection('users', function (err, collection) {
If (err) {
          mongodb.close();
          return callback(err);//Error, return err information
}
//Find a document whose username (name key) value is name
      collection.findOne({
name: name
}, function (err, user) {
          mongodb.close();
If (err) {
             return callback(err);//Failed! Return err information
}
​​​ callback(null, user);//Success! Return the queried user information
});
});
});
};

Here is one for writing data and one for reading data. We have the processing program. Now we need to add the following program in front of index.js

Copy code The code is as follows:
var User = require('../models/user.js' );

Modify app.post('/register')

Copy code The code is as follows:

app.post('/register', function (req, res) {
var name = req.body.name;
var pwd = req.body.password;
var newUser = new User({
name: name,
Password: pwd
});
newUser.save(function (err, user) {
//Related operations, write to session
res.send(user);
});
});

Then click register and you will get a response

If you are not sure whether to write to the database at this time, you can enter the database to query, first switch to the database directory

Copy code The code is as follows:
D:mongodbbin>

Enter:

Copy code The code is as follows:
mongo

Then switch its database connection to blog

Copy code The code is as follows:
use blog

Last input

Copy code The code is as follows:
db.users.find()

We were all happy to see the data written, so today’s study comes to an end for now

Conclusion

Today we followed a blog to complete the operation from installation to writing to the database. Tomorrow let us add other aspects and gradually deepen the learning of nodeJS

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

The difference between nodejs and vuejs The difference between nodejs and vuejs Apr 21, 2024 am 04:17 AM

Node.js is a server-side JavaScript runtime, while Vue.js is a client-side JavaScript framework for creating interactive user interfaces. Node.js is used for server-side development, such as back-end service API development and data processing, while Vue.js is used for client-side development, such as single-page applications and responsive user interfaces.

Is nodejs a backend framework? Is nodejs a backend framework? Apr 21, 2024 am 05:09 AM

Node.js can be used as a backend framework as it offers features such as high performance, scalability, cross-platform support, rich ecosystem, and ease of development.

How to connect nodejs to mysql database How to connect nodejs to mysql database Apr 21, 2024 am 06:13 AM

To connect to a MySQL database, you need to follow these steps: Install the mysql2 driver. Use mysql2.createConnection() to create a connection object that contains the host address, port, username, password, and database name. Use connection.query() to perform queries. Finally use connection.end() to end the connection.

What is the difference between npm and npm.cmd files in the nodejs installation directory? What is the difference between npm and npm.cmd files in the nodejs installation directory? Apr 21, 2024 am 05:18 AM

There are two npm-related files in the Node.js installation directory: npm and npm.cmd. The differences are as follows: different extensions: npm is an executable file, and npm.cmd is a command window shortcut. Windows users: npm.cmd can be used from the command prompt, npm can only be run from the command line. Compatibility: npm.cmd is specific to Windows systems, npm is available cross-platform. Usage recommendations: Windows users use npm.cmd, other operating systems use npm.

What are the global variables in nodejs What are the global variables in nodejs Apr 21, 2024 am 04:54 AM

The following global variables exist in Node.js: Global object: global Core module: process, console, require Runtime environment variables: __dirname, __filename, __line, __column Constants: undefined, null, NaN, Infinity, -Infinity

Is there a big difference between nodejs and java? Is there a big difference between nodejs and java? Apr 21, 2024 am 06:12 AM

The main differences between Node.js and Java are design and features: Event-driven vs. thread-driven: Node.js is event-driven and Java is thread-driven. Single-threaded vs. multi-threaded: Node.js uses a single-threaded event loop, and Java uses a multi-threaded architecture. Runtime environment: Node.js runs on the V8 JavaScript engine, while Java runs on the JVM. Syntax: Node.js uses JavaScript syntax, while Java uses Java syntax. Purpose: Node.js is suitable for I/O-intensive tasks, while Java is suitable for large enterprise applications.

Is nodejs a back-end development language? Is nodejs a back-end development language? Apr 21, 2024 am 05:09 AM

Yes, Node.js is a backend development language. It is used for back-end development, including handling server-side business logic, managing database connections, and providing APIs.

How to deploy nodejs project to server How to deploy nodejs project to server Apr 21, 2024 am 04:40 AM

Server deployment steps for a Node.js project: Prepare the deployment environment: obtain server access, install Node.js, set up a Git repository. Build the application: Use npm run build to generate deployable code and dependencies. Upload code to the server: via Git or File Transfer Protocol. Install dependencies: SSH into the server and use npm install to install application dependencies. Start the application: Use a command such as node index.js to start the application, or use a process manager such as pm2. Configure a reverse proxy (optional): Use a reverse proxy such as Nginx or Apache to route traffic to your application

See all articles