Nodejs tutorial environment installation and operation_node.js
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:
Then there may be dependent packages inside. We need to enter the blog directory to install (the installation configuration is provided by package.json):
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:
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
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
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:
/**
* 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:
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
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
This sentence means that error messages should be output during development
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:
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
The above code can be replaced by this code (written in the app)
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:
Then modify index.js
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
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:
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
app.get('/register', function (req, res) {
res.render('index', { title: 'Registration page' });
});
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' });
});
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
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
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
{
"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
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
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});
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
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
});
});
});
};
//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
Modify app.post('/register')
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
Enter:
Then switch its database connection to blog
Last input
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

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Python is more suitable for data science and machine learning, while JavaScript is more suitable for front-end and full-stack development. 1. Python is known for its concise syntax and rich library ecosystem, and is suitable for data analysis and web development. 2. JavaScript is the core of front-end development. Node.js supports server-side programming and is suitable for full-stack development.

JavaScript does not require installation because it is already built into modern browsers. You just need a text editor and a browser to get started. 1) In the browser environment, run it by embedding the HTML file through tags. 2) In the Node.js environment, after downloading and installing Node.js, run the JavaScript file through the command line.

How to send task notifications in Quartz In advance When using the Quartz timer to schedule a task, the execution time of the task is set by the cron expression. Now...


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Zend Studio 13.0.1
Powerful PHP integrated development environment

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)