The article directories
-
-
-
- Writing in the front
- What is a NodeJS
- Why is NodeJS so popular
- Using NodeJS requires a lot of skill
- Install NodeJS
- Verify the installation
- Tool use
- NodeJS global variables for starters
- Understanding the global
- Introduction to the V8 engine
- Module Introduction (Node module)
- Event module
- FileSystem (read/write fs-filesystem)
-
-
Writing in the front
Nonsense first say good, otherwise you see behind impatient later will not see me to say nonsense, why I write this series of node articles? I’ve noticed that nodeJS is becoming more and more of a requirement from many companies (although I don’t know why, perhaps because they feel that their companies are too powerful and need someone who can handle nodeJS), so I thought it would be worth reviewing a few things about NodeJS anyway. I carding process there may be some not rigorous, but basically is largely right, although you as a reference, it involves the source code is running on my own future, so there is nothing wrong with basic, holding the manner which worthy fan writing articles, or to be responsible for their own fans (though few fans), Finally, I hope that after reading my article, I can have a new or new understanding of NodeJS. I hope you can timely mention any mistakes or loose points. After all, I am just a programmer who is not so strict but has an attitude. Because I have to go to work, so I can only update it at night after work, slowly, EMmm… It’s a little too much nonsense, let’s get started…
What is a NodeJS
- Node.js is a JavaScript runtime environment for the basic Chrome V8 engine
- Node.js uses an event-driven, non-blocking I/ O model, making it lightweight and efficient
- Node.js package manager NPM (Node Package Mange) is the largest open source library ecosystem in the world
Why is NodeJS so popular
- Javascript is used
- Very fast
- Nodejs’ package manager is the largest open source library in the world
- Can save resources, what do you mean, if our project is not very big, processing of data is not very complex, we use nodejs is enough, that is to say before we make a data interaction program requires at least two people, write a front-end a back end, but the company project is not very big words, A person who knows NodeJS is perfectly capable of doing database operations.
Using NodeJS requires a lot of skill
- Command Line
- Html+css
- javascript
- Mongo DB (this is a non-relational database, we nodeJS choose to connect to it, because the query speed of a non-relational database is very fast, because there is no association between the table, unlike our myqSQL or Oracle relational database, Nodejs is a high concurrency language, so the speed of data operation is very high. Mongo DB is selected here.
Install NodeJS
- Node
- The Node to learn
- Download the end of the direct installation can be
Verify the installation
Enter node -v directly
NPM – v input
Or we can run one of our native js files directly, which is the same as node csdn_demo.js
Tool use
- Webstorm (download and use webStorm directly, here does not write the download and installation process)
- Vscode (personally recommended to use this, this is a relatively lightweight editor, the important thing is that you can customize your own plug-in)
- Sublime (This is the best to use I think, but getting started is a bit more difficult)
NodeJS global variables for starters
For example
/ * * *@author clearlove
* @aim Test a nodeJS global variable *@param Time The timing variable *@param Timer Clears a timer * setTimeout Indicates a delay * setInterval Indicates a timer cycle */
setTimeout(function () {
console.info("Three seconds have passed and I'm done executing.")},3000)
var time = 0
let timer = setInterval(function () {
time++
console.info(time)
if (time > 10) {
clearInterval(timer)
console.info("It's over.")}},2000)
Copy the code
- The results
There’s another thing we see a lot
console.info(__dirname) //w file path name does not contain the file name. This is also a global variable in bNode
console.info(__filename) // The full path name of the file
Copy the code
Understanding the global
Global is a node variable, but it is a node variable. The reason is that it has its own different place, we all know that the js global variable is Windows, we are generally Windows. A property, but in Node its boss is global, so let’s just print this out and see what it is
console.info(global)
Copy the code
– I won’t show the results here, you can run it yourself, it’s too long, screenshot or direct copy is not friendly.
Introduction to the V8 engine
- First of all, let’s talk about why we need this engine and what it does. As we all know, our computer does not know what javascript we write, and the backend languages that the computer can recognize, such as C and C++, can recognize, but it does not know our JS. Node is written in C++. V8 engine is the core of nodejs. V8 engine is actually written in C++. The process is to write good JS code through v8 engine running in the Node environment, so as to achieve a computer to understand our JS language effect, a simple draw a foot of the flow chart, MD document drawing flow chart is relatively simple (CAodan).
- Here is my understanding, there may be some deviation, if there is any problem, inform me in time, I will update the content in time.
Module Introduction (Node module)
- When we write code, the general rule of development is the development of one function and one module, which is not only easy to develop, but also more convenient in order to avoid scolding you when others receive your code in future maintenance. So it’s the same in Node, every JS is a module. Then write a total js unified call. Let’s write a simple example:
- – We create a new tool class js, this purpose is for the user to input a data type, we output his data type
/ * * *@auhor clearlove
* @aim Determine the data type entered by the user *@param {*} Params parameters * /
var counter = function(params) {
return typeof params
}
// Export the current utility function to a place where it can be used directly
module.exports = counter
Copy the code
We introduce it in node_demo.js
/ * * *@author clearlove
* @aim Receive module code *@parms Counter assigns the incoming js to counter */
let counter = require("./stuff")
console.info(counter(false))
Copy the code
Operation effect:
Module. Exports: require
- Module. exports aims to export current utility functions to a place where they can be imported, so they can be imported elsewhere
- Require directly imports the JS we need, why do we need a variable to receive it? Because if we don’t accept it we still can’t find a way to quote it
So, at this point, people are asking, what if we have one method and we have more than one? See the examples:
- stuff.js
/ * * *@auhor clearlove
* @aim Determine the data type entered by the user *@param {*} Params parameters * /
var counter = function(params) {
return typeof params
}
/ * * * *@param {*} a
* @param {*} b
*/
var add = function(a, b) {
return 'The result of the calculation is:${a+b}`
}
/ * * *@param PI PI */
var pi = 3.141592653589793238462643383279
// Export the current utility function to a place where it can be used directly
module.exports.counter = counter
module.exports.add = add
module.exports.pi = pi
Copy the code
- node_demo.js
/ * * *@author clearlove
* @aim Receive module code *@parms Counter assigns the incoming js to counter */
let stuff = require("./stuff") // Stuff is an object
console.info(stuff.counter(false))
console.info(stuff.add(584.654))
console.info(stuff.pi)
Copy the code
- The results
If you want to copy a hundred methods a hundred times, you can export an object directly and look at the code:
/** * export each method name to */
module.exports = {
counter: counter,
add: add,
pi: pi
}
Copy the code
- I’m not going to show the results here, but it’s the same as above. There is also the value of the object above you write your method is also ok, look at the code:
/ * * *@param PI PI */
var pi = 3.141592653589793238462643383279
/** * export each method name to */
module.exports = {
counter: function(params) {
return typeof params
},
add: function(a, b) {
return 'What you calculate is:${a + b}`
},
pi: pi
}
Copy the code
${a+b} ${a+b} ${a+b} ${a+b} ${a+b} ${a+b} ${a+b}
Event module
- Events we often encounter in JS, such as mouse click, keyboard events, etc., events are to solve interaction problems, so node also has Event module, he is the three points we need to pay attention to the Event here: The Nodejs core API uses the traditional asynchronous EventEmitter architecture (FS/HTTP). All EventEmitter objects are instances of the EventEmitter class. The sequence of events is as follows: Import modules -> Create EventEmitter objects -> register events -> trigger events
- See the example
/ * * *@author clearlove
* @aim Demonstrates the basic event usage process *@param MyEmitter creates the EventEmitter object */
Import event from 'events' import event from 'events' is written in the same way as below, except that it is written in ES6
var event = require('events');
// Create the EventEmitter object
var myEmitter = new event.EventEmitter();
Function ('click',function (params) {}) {// Register an event ('click',function (params) {}))
myEmitter.on('anyevent'.function(param){
console.info(typeof param)
//return typeof param
})
You can call the event directly or pass arguments
//myEmitter. Emit ('anyevent',false) //myEmitter. Emit ('anyevent',false
myEmitter.emit('anyevent'.false)
Copy the code
Running results:
- To handle asynchronous execution:
/ * * *@author clearlove
* @aim Demonstrate asynchronous use *@param MyEmitter creates the EventEmitter object */
var event = require('events');
var myEmitter = new event.EventEmitter();
myEmitter.on('anyevent'.function(param){
console.info(param)
})
myEmitter.emit('anyevent'.'I'm myEmitter event.')
console.info('I'm being executed after the myEmitter event.')
Copy the code
Running results:
We can see that our code is executed sequentially, that is, the following events are executed after the execution of the above declared events, so what if I want to reverse the execution order? Node’s official solution looks like this:
/ * * *@author clearlove
* @aim Demonstrate asynchronous use *@param MyEmitter creates the EventEmitter object */
var event = require('events');
var myEmitter = new event.EventEmitter();
myEmitter.on('anyevent'.function(param){
EventEmitter calls all listeners synchronously in the order in which they were registered. You must ensure that events are ordered correctly and race conditions are avoided. SetImmediate () or process.nexttick () can be used to switch to asynchronous mode
setImmediate(() = >{
console.info(param)
})
})
myEmitter.emit('anyevent'.'I'm myEmitter event.')
console.info('I'm being executed before the myEmitter event.')
Copy the code
Running results:
I don’t need to write down any of the following methods: once, error, or whatever. Multiple parameter case handling, look at the code:
/ * * *@author clearlove
* @aim Demonstrate multiple arguments *@param MyEmitter creates the EventEmitter object */
var event = require('events');
var myEmitter = new event.EventEmitter();
myEmitter.on('event'.(a, b) = > {
console.log(a + b,this);
});
myEmitter.emit('event'.1.2);
Copy the code
Running results:
When a listener is called, this points to the EventEmitter object
FileSystem (read/write fs-filesystem)
- File systems are usually used for reads and writes, while others are rarely used. Node is also used for reading and writing files.
- readFile (fs.readfile) - writeFile (fs.writefile) - flow: introduce fs module -> call method -> exception captureCopy the code
- Synchronously reading and writing files
/ * * *@author clearlove
* @aim Demo file read and write *@param MyEmitter creates the EventEmitter object */
/ / introduction of the fs
var fs = require('fs');
// Read file synchronously through object call method
var readme = fs.readFileSync('readMe.txt'.'utf-8');
console.info(readme)
fs.writeFileSync('writeMe.txt',readme) // Write files synchronously
Copy the code
Running results:
You’ll notice that when you write the file there’s an extra file underneath that we just wrote
- Asynchronously read and write files to see the code:
/ * * *@author clearlove
* @aim Demo file read and write */
/ / introduction of the fs
var fs = require('fs');
/ * * *@readMeTXT Files to be read *@utf-8 Read character format *@error Throw an exception@data What to read */
fs.readFile(__filename,'utf-8'.function (error,data) {
if(error) throw error
// Write its contents to a new file after we finish reading
writeMeSync(data)
})
/ * * *@writeMeSync Write to a file *@param {*} Write the argument */
function writeMeSync(params) {
fs.writeFile('SyncWriteMe.txt',params,function(error,data){
if(error) throw error
})
}
Copy the code
– Running results:
- Create files and delete files
- Create folder fs.mkdir - delete folder fs.rmdir - Delete file fs.unlink process: introduce fs module -> Call method -> exception captureCopy the code
Look at the code:
/ * * *@author clearlove
* @aim Demonstrates deleting files and folders */
/ / introduction of the fs
var fs = require('fs');
fs.unlink('SyncWriteMe.txt'.function (err) {
if (err) throw err
console.info('Deleted successfully')})// Create a folder
fs.mkdirSync('views'.function(err){
if (err) throw err
console.info('Created successfully')})// Delete the folder
fs.rmdirSync('views'.function(err){
if (err) throw err
console.info('Deleted successfully')})Copy the code
- Run it yourself
- Deleting files asynchronously
/ * * *@author clearlove
* @aim Demonstrates deleting files and folders */
/ / introduction of the fs
var fs = require('fs');
Create a new folder, read the current file contents, and write the latest file contents to a new file
fs.mkdir('views'.function () {
fs.readFile(__filename, 'utf-8'.function (err, data) {
if (err) throw err;
fs.writeFile('./views/new.js', data,function(err){
if(err) throw err
console.info('Created successfully')})})})// Delete the folder asynchronously before deleting the folder, the folder is empty, so the first step is to delete the files in the folder, and then delete the folder
fs.unlink('./views/new.js'.function (err) {
if(err) throw err
fs.mkdir('vires'.function (err,data) {
if(err) throw err
console.info('Folder deleted successfully')})})Copy the code
- Running results:
Ok, first wrote here, NodeJS still have a lot to learn, but can not be achieved overnight, do things step by step, the next time the time of writing the rest of the some knowledge about NodeJS, because I am a self-taught, so write some non-standard or have questions to ask me where I change directly, Learning NodeJS is bound to be a long way down the road. In the next article I will write about how to run a service locally and render local HTML, as well as concepts about buffer and Stoream streams. Thank you.