Try to use Node.js to stumble and stumble in your work. Briefly comb Noejs (7 days) from now on, leaving out the following points of knowledge in the example section:
require and export
Export methods or variables from a file using the export or module.exports method in the target component
The difference is that export is not available when exporting a single variable or method
A simpler way to distinguish: forget how export is exported
require is used to accept functions or methods that components export through module.export
// a.js export function add (e) { ...... } module.exports.add(e) // b.js import var a = require('a') a.add(1) // Using methods in a.js
Exporting through the export or module.export method is a collection of objects
http core module
var http = require('http') // Introducing http core modules var server = http.createServer() // Create a server service server.on('request', (request, response) => { // Request to get request data // Response returns response data }) server.listen(3000, () => {...}) // Listen on port number 3000
url core module
-
url.parse(urlStr[, parseQueryString[, slashesDenoteHost]])
urlStr url string
When parseQueryString is true, the query string will be parsed using the query module, defaulting to false
-
url.pathname
Gets and sets the path portion of the URL
-
url.query
Get the URL parameter section (? After)
Assume the page request address is/url?Name=sfatpaper&data=20191129
var http = require('http')// Introducing http core modules var url = require('url') // Introducing url core modules http.createServer((req, res) => { var parseObj = url.parse(req.url, true) // Use the url.parse method to get the object requesting the URL var pathName = parseObj.pathname // /url var pathQuery = parseObj.query // {name: sfatpaper, data: 20191129} // var parseObj = url.parse(req.url) // var pathQuery = parseObj.query // name=sfatpaper&data=20191129 })
Nodemon
Nodemon is a usage tool that will meet to monitor any changes in the source file and automatically restart the server.Nodemon doesn't make any additional changes to your code, it's just a replacement for the node command
install
npm install --global nodemon
Example
// Change node demo.js of previously run code to nodemon demo.js
art-template template engine
art-template is a simple, ultra fast template engine
install
npm install art-template --save
Example
var template = require('art-template') // Introducing art-template components template.render(source, data, options) // The template string source needs to export // Data needs to be replaced with a data object in the template string
Express Framework
Be based on Node.js Platform, Fast, Open, Minimalist Web Development Framework
install
npm install express --save
Example
var express = require('express') // Introducing express components var app = express() app.get('/', (req, res) => res.send('Hello World!')) // Processing get requests app.listen(3000, () => {...}) // Listen on port number 3000
Express-art-template
Express-art-template is a third-party component specifically designed to support the template template engine in Express
install
npm i art-template
To configure
app.engine('html', require('express-art-template'))
Example
app.engine('html', require('express-art-template')) // Configure art-template app.render(source, data, options) // The template string source needs to export // Data needs to be replaced with a data object in the template string
body-parser
express does not provide a way to get the corresponding requester in the post request mode, so the body-parser component is needed to process the response request
install
npm install --save body-parser
To configure
app.use(bodyParser.urlencoded({ extended: false })) app.use(bodyParser.json())
Example
var bodyParser = require('body-parser') // Introducing components app.use(bodyParser.urlencoded({ // Configuring components extended: false })) app.use(bodyParser.json()) app.post('/post', (req, res) => { console.log(req.body) // req.body gets post body })
MongoDB database
MongoDB is a non-relational database
install
Installation File Download Address: [ https://www.mongodb.com/download-center/community]
Special attention is required during installation to remove the default check before Install MongoDB Compass
You can use the mongod --version command to view the MongoDB version and install it if the version number output is normal
Use
- Start database mongodb By default, the database directory launched by the command executes in the drive letter root directory/data/db file where the command executes
- Replace database directory mongod --dbpath ='Database self-proposed path'
- Connect MongoDB service mongodb
- Show all existing databases show dbs
- Switch to target database use'Database name'
- View current operational database db
- Displays all collections of the current database show'Database name'
- Displays all data in the database collection db.'Database name'.find()
- Add data db.'Database name'.insertOne({data object}) to the database collection
- Disconnect the MongoDB service exit
A visual Mongodb software NoSQLBooster for MongoDB
Download address: NoSQLBooster - The Smartest GUI Admin Tool for MongoDB
Mongoose
Mongoose is an object model tool that facilitates the operation of mongodb in the node.js asynchronous environment
install
npm install mongoose
Example
var mongoose = require('mongoose'); // Introducing mongoose mongoose.connect('mongodb://localhost/test'; //connect to mongodb database via mongoose
The default port to connect to the database is 27017
var db = mongoose.connection; // Database Connection Status db.on('error', console.error.bind(console, 'connection error:')); // Database Connection Failure db.once('open', function() { // we're connected! (Database connection successful) });
.connection returns a pending connection that we can monitor for success
var Kitten = mongoose.model('Kitten', mongoose.Schema({ // name: String, // You can also write as follows name: { type: String, // data type required: Boolean, // Is it necessary defaule: 'Zhang San', // Default value enum: ['Zhang San', 'Li Si', 'King Five', 'Zhao Six'] // Enumeration, default value is only enumeration value } }); );
Before you can manipulate the database, you need to pre-design the data formats in the collection, such as the code above
A collection named Kitten was created with a data name and a string type in the data structure inside the collection
-
Add data
Model.save([fn])
var user = new User({ // Add a new data username: 'kongzhi0707', password: '123456' }); user.save(function(err, res) { // Save data in database if (err) { return console.log(err); } console.log(res); });
-
Delete data
Model.remove(conditions, [callback]) Deletes all eligible documents from the collection
Model.findByIdAndRemove(id, [options], [callback]) Finds documents matching the ID and deletes them
Model.findOneAndRemove(conditions, [options], [callback]) by record
var wherestr = {'username': 'kongzhi0707'}; // Conditions for deleting data User.remove(wherestr, function(err, res) { if (err) { return console.log(err); } console.log(res); });
-
Update Data
Model.update(conditions, doc, [options], [callback]) Updates a document in the database based on conditions
Model.findByIdAndUpdate(id, [update], [options], [callback]) Updates a document in the database through its ID field
Model.findOneAndUpdate([conditions], [update], [options], [callback]) based on record
var wherestr = {'username': 'kongzhi0707'}; // Conditional queries to update data var updatestr = {'password': 'abcdef'}; // Perform Update Data User.update(wherestr, updatestr, function(err, res) { if (err) { return console.log(err); } console.log(res); });
-
Query Data
Model.find(conditions, [fields], [options], [callback]) Finds files based on conditions
Model.findById(id, [projection], [options], [callback]) finds a single document through its ID field
Model.findOne([conditions], [projection], [options], [callback]) based on records
var wherestr = {'userName': 'Lon 0707'}; // Conditions for deleting data User.find(wherestr, function(err, res) { if (err) { return console.log(err); } console.log(res); });
The article has synchronized with my personal blog: ' Node Learning Notes 7-day Course Knowledge Arrangement>
Related articles:
- Node Learning Notes fs.readFile, fs.writeFile, fs.readdir
- Node Learning Notes http.createServer, art-template
- Node Learning Notes express, express-template, nodemon
- Node learning notes post, express for comment submission
- Node's Learning Notes Mongodb and Monoose
Reference:
- [Document Node.js v12.13.1]
- [art-template high performance JavaScript template engine]
- [Express - web Application Development Framework Based on Node.js Platform]
- [MongoDB website]
- [Mongoose.js Chinese Web]
This article is published by blog OpenWrite Release!