This article has participated in the third “topic writing” track of the Denver Creators Training Camp. For details, check out: Digg Project | Creators Training Camp third is ongoing, “write” to make a personal impact
review
To cut to the chase, the conclusion:
- File to read and write
- Network request
- The callback function
These are definitely the three core basics that you need to know to develop with Node.js, and let’s take a look at each of them and explain why they are essential.
The overall cognitive
The first step is to figure out what Node.js is and why it’s called “runtime.” To put it this way, JavaScript is a programming language, and code written in JavaScript needs some environment to run it.
JavaScript was originally created to perform some simple logic in the browser and implement some web page adjustment functions. So at that time JavaScript was running within the execution environment provided by the browser, which means that the browser had something inside the program that could execute JavaScript, you could call it a compiler, you could call it an interpreter, so the logic of the code that was written in JavaScript could be run inside the browser.
JavaScript’s syntax was found to be friendly and easy to learn, so it was used to create Node.js, which is also an environment where you can run JavaScript code, and which allows you to access operating system files and network resources using JavaScript code.
The concept,
File to read and write
Node.js is a powerful programming language that allows you to access and manipulate various resources on your computer, such as computer memory, processes, files, etc.
The premise is to install Node.js on a computer and write code using node.js syntax. The download can be done here, and you can write the code just by following the conventions of JavaScript programming. JavaScript inside the browser can access browser-provided apis such as window.alert(), console.log(), etc.
Node.js also has a set of apis provided by its environment. Some apis reside on global objects as browsers do, while others are encapsulated within modules.
For example, the API for reading and writing files, you need to use it in your code by introducing the FS module, which stands for “File System”.
Suppose we have a readme.md file that reads as follows
# titles a
Copy the code
We can read the contents of this file using the following code
const fs = require('fs');
const file = fs.readFileSync('./readme.md');
console.log(file.toString())
Copy the code
The output
# titles aCopy the code
Similarly, we can use the corresponding API to write files, as follows
const fs = require('fs');
fs.writeFileSync('./out.md'.'# out')
Copy the code
You will find an out.md file in the current directory, with the following contents
# out
Copy the code
Network request
It’s not enough just to be able to access local files, we also need to take advantage of the power of the web to access content on the web. Browsers have limited access to network resources due to the same origin policy, while in Node.js, HTTP and HTTPS modules can be used to obtain various network resources.
For example, we create a Node.js file like this
const https = require('https');
const api = 'https://api.juejin.cn/user_api/v1/author/recommend?limit=5'
https.get(api, res= > {
let content = ' ';
res.on('data'.chunk= > {
content += chunk;
})
res.on('end'.() = > {
console.log(JSON.parse(content)); })})Copy the code
Five recommended users will be output from the nuggets homepage, as follows
{
err_no: 0,
err_msg: 'success',
data: [
{
user_id: '4388906148312295', user_name: '_ red scarf ', got_digg_count:466,
got_view_count: 113613,
avatar_large: 'https://sf6-ttcdn-tos.pstatp.com/img/user-avatar/20d58b6931ec0610487b6be50ff91aaa~300x300.image',Company: ", job_title: ", level:3,
description: '',
author_desc: '',
isfollowed: false
},
{
user_id: '131597122679661', user_name: 'Cloud world ', got_digg_count:7535,
got_view_count: 232528,
avatar_large: 'https://sf1-ttcdn-tos.pstatp.com/img/user-avatar/f1a9f122e925aeef5e4534ff7f706729~300x300.image',Company: 'wechat: dirge-cloud', job_title:' front-end engineer ', level:4See the world hear the world ask the world. ', author_desc: '', isfollowed:false
},
{
user_id: '3298190614865997',
user_name: 'artist',
got_digg_count: 774,
got_view_count: 66671,
avatar_large: 'https://sf6-ttcdn-tos.pstatp.com/img/user-avatar/84361adb9ca86b8f149ba57b16bbe56c~300x300.image',Company: 'Artist studio ', job_title:' Front-end development ', level:3,
description: '',
author_desc: '',
isfollowed: false
},
{
user_id: '1415826704971918', user_name: got_digg_count:4124,
got_view_count: 224713,
avatar_large: 'https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/gold-user-assets/2019/6/2/16b17bc6f37d2e4e~tplv-t2oaga2asx-image.image',Company: ", job_title: ", level:4,
description: '',
author_desc: '',
isfollowed: false
},
{
user_id: '2365804752407480', user_name: 'yufei ', got_digg_count:2379,
got_view_count: 60277,
avatar_large: 'https://sf1-ttcdn-tos.pstatp.com/img/user-avatar/54a24fe455719e158f4ab41863399272~300x300.image',Company: ", job_title: ", level:3, description: 'Follow the problem a little longer ', AUTHOR_desc: ', isfollowed:false
}
],
cursor: '5',
count: 99,
has_more: true
}
Copy the code
This is actually the source of the “author list” on the right side of the Nuggets’ homepage, which can be viewed by clicking on the “Full List.
Isn’t it amazing that not all of the interface data is available to us? In general, important data interfaces do something to prevent us from accessing the results so easily, but this demonstrates the power of Node.js to access network resources through network modules.
The callback function
Next, we need to explain the “callback function” thing, because node.js is full of callback functions in its design. Node.js is an “asynchronous event-driven” JavaScript runtime, and callbacks are the basic way JavaScript implements asynchro.
The first thing we need to know is that a callback function is also a function, but it is used for “callback execution.” To break it down, a function is a block of code that is declared in JavaScript to perform some specific logic in one of two ways
function a (msg) {
console.log(msg);
}
a('hello');
Copy the code
var b = function (msg) {
console.log(msg);
}
b('world');
Copy the code
The first of these is called a function declaration, and the latter is called a function expression.
Declaration is the use of the function keyword to declare variable A as a function, and then use this variable to call the function. An expression is a basic operation in a programming language. Just like declaring a normal variable, a function expression assigns a value to a variable whose content is the function, so calling the function is executed using the variable and parentheses.
The “callback” concept comes from the fact that JavaScript can take one function as an argument to another, as shown in the code below
function a (callback) {
const msg = 'hello';
callback(msg);
}
function b (msg) {
console.log(msg);
}
a(b);
Copy the code
Here we declare two functions. The argument of function A receives another function, and its internal execution logic is “first assign a variable MSG with a value of hello, then take MSG as an argument and execute the function passed in as the argument”. The logic of function B is to simply print the value of the variable passed in.
When function A is executed, we pass function B as an argument to function A, so that the logic executed inside function A to callback(MSG) is called “callback function execution”, which is called “callback function”.
Now that you understand the concept of callback functions, let’s look at the example in the network request
const https = require('https');
const api = 'https://api.juejin.cn/user_api/v1/author/recommend?limit=5'
https.get(api, res= > {
let content = ' ';
res.on('data'.chunk= > {
content += chunk;
})
res.on('end'.() = > {
console.log(JSON.parse(content)); })})Copy the code
Get is calling the get method in HTTPS module (method is another name for function in some sense). The parameters we pass to get function are API and another function respectively, where API is a common variable and its content is the address of a network resource, and the other function is our callback function.
We can write it out separately
const https = require('https');
const api = 'https://api.juejin.cn/user_api/v1/author/recommend?limit=5'
function callback (res) {
let content = ' ';
res.on('data'.chunk= > {
content += chunk;
})
res.on('end'.() = > {
console.log(JSON.parse(content));
})
}
https.get(api, callback);
Copy the code
This looks more like our example above, where HTTPS. Get is our a function and callback is our B function. This is the first place the callback is used here, as is the second argument in res.on(‘data’) where the callback is used in second place, and the second argument in res.on(‘end’) where the callback is used in third place.
Most of the apis in Node.js are used in this way, so mastering the callback function is one of the core foundations of Node.js. Of course, Node.js has evolved in other ways to handle asynchronous operations, but the callback function is still its most basic implementation.
conclusion
To summarize, we’ve learned the basic core concepts of file reading and writing, network requests, and callback functions, which are essential for node.js development as well as for many other programming languages. So a good understanding of these concepts is crucial to learning software development.
Also, once you’ve mastered these three things, you’re almost ready to use most of Node.js, and more functionality may come in combinations of the three, combined with other basic capabilities. If you’re interested in Node.js development, install node.js and get started.