1. Uncle Wolf: How to learn Node.js correctly

I5ting.github. IO/how-to Lear…

Introduction of Live

Hello, I am I5ting, known as “Uncle Wolf”. I am currently a technical expert of Alibaba, star lecturer of StuQ and evangelist of Node.js technology. I have worked in Qunar, Sina and Netqin, and have done front-end, back-end and data analysis. I am a practitioner of full-stack technology.

Now, more and more technology companies and developers are using Node.js to develop a variety of applications. Node.js can also write Web applications, encapsulate apis, assemble RPC services, and even develop PC clients like VSCode editors. Compared to other technologies, Node.js is simple to learn, performs well, and is easy to deploy, making it easy to handle large numbers of server requests in high-concurrency scenarios. The ecosystem around Node.js is also very strong, with over 600,000 modules on NPM (Node package management) and over 300 million downloads per day. However, writing Node.js code is not an easy task for newcomers and developers from other languages, and there are many complex concepts that need to be understood before getting started.

A lot of people around me ask me: How do I learn Node.js? As a Node.js evangelist, I have done a lot of work on node.js popularization and promotion, and I am familiar with its basic concepts and core modules; In addition, I’ve been working on a book called “The Better Node.js” for two years now, which has accumulated a wealth of material, and this Live will provide you with a more comprehensive interpretation of Node.js.

This Live mainly includes the following contents, contents

Part 0: Introduction to Node.js

A) Node.js b) What is Node.js? C) Fundamentals

Part 1 Introduction: Learn the three states of Node.js

Part 2 Preparation: How to learn Node.js

  • 2.1 Node has so many uses, where do I start?
  • 2.2 Node Web Framework so many, how should I choose?
  • 2.3 Books on Node are almost out of date. Which one should I buy?

Part 3 Extension: The big front end changes so fast, how can we achieve daily improvement?

Part 4 Practice: From a recruitment perspective, what skills are needed for Node.js development?

Part 5 Q & A: Answer your questions

This Live is mainly popular science, suitable for new users and more confused Node friends, we hope you understand and support.

1.1. Part 0: Introduction to Node.js

A) Node.js b) What is Node.js? C) Fundamentals

1.1.1.a) Introduction to Node.js

Node.js was developed in 2009 by Joyent employee Ryan Dahl, and the company has been the incubator of Node.js ever since. Ryan left the community in 2012 for a number of reasons, followed by disagreements between Node contributors over the integration of new ES6 features in 2015, which led to the split of IOJS and the release of versions 1.0, 2.0, and 3.0 by IOJS. The split of IOJS eventually led to the establishment of the Node Foundation in 2015 and the smooth release of version 4.0. The founding members of the Node.js Foundation include Google, Joyent, IBM, Paypal, Microsoft, Fidelity and the Linux Foundation. The founding members will co-manage the Open source Node.js project, which was previously controlled by Joyent alone. Since then, node.js Foundation has been developing very well, steadily releasing versions 5, 6, 7, 8, etc. By the time of writing, the latest version is 8.6, and the long-term support version is 6.11.

Node.js is neither a language nor a framework. It is a JavaScript runtime environment based on Google V8 engine, with Libuv extending JavaScript functionality to support language-only features such as IO and FS. Enable JavaScript to simultaneously have DOM manipulation (browser) and I/O, file read and write, operation database (server side) and other capabilities, is the simplest full-stack language.

As early as 2007, Jeff Atwood proposed the famous Atwood law

Any application that can be implemented in JavaScript will eventually be implemented in JavaScript

Node.js currently has a niche in most areas, especially I/O intensive ones such as Web development, microservices, front-end builds, etc. Many large websites use Node.js as the background development language, and most of them use Node.js to do front-end rendering and architecture optimization, such as Taobao Double 11 and Qunar’s PC core business. In addition, there are a number of well-known front-end libraries developed using Node.js. For example, Webpack is a powerful wrapper, and React/Vue is a mature front-end componentalization framework.

Node.js is typically used to develop low-latency web applications, that is, applications that need to collect and exchange data in real time (apis, instant chat, microservices) both in a server-side environment and on the front end. Alibaba, Tencent, Qunar, Baidu, PayPal, Dow Jones, walmart and LinkedIn all use the Node.js framework to build applications.

In addition, The Package manager NPM written by Node.js has become the best ecosystem of open source package management in the field. As of October 2017, there are more than 470,000 modules, more than 3.2 billion downloads per week, and more than 7 million developers use NPM every month.

Of course, Node.js does have some drawbacks. Node.js is often teased for having too many callbacks that are hard to control (commonly known as callback hell) and not handling cpu-intensive tasks very well. However, asynchronous process technology has made great progress, from Callback and Promise to Async functions, which can easily meet all development needs. As far as cpu-intensive task handling is concerned, there are many alternatives, such as extending Node.js with the underlying system language Rust, but this can be a bit cumbersome. I’m a big believer in using the right things in the right context, especially in a microservice architecture where everything is a service and language agnostic. If you want JavaScript to do CPU-intensive tasks, we recommend fibJS, node. js’s sibling project, based on fiber (which can be simply interpreted as a more lightweight thread), which is very efficient, compatible with NPM, and does not have the worry of asynchronous callback.

1.1.2. b) What is Node.js?

According to the homepage of node.js:

Node.js® is a JavaScript runtime built on Chrome's V8 JavaScript engine. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient. Node.js' package ecosystem, npm, is the largest ecosystem of open source libraries in the world.
Copy the code

From this introduction, the main points of interpretation are as follows

  • Node.js is not a JavaScript application, it’s not a language (JavaScript is a language), it’s not a framework like Rails(Ruby), Laravel(PHP), or Django(Python), It’s not a Web server like Nginx. Node.js is a JavaScript runtime environment
  • Built on Chrome’s V8 this famous JavaScript engine, Chrome V8 engine C/C++ based, equivalent to the use of JavaScript, converted into C/C++ calls, greatly reduce the cost of learning
  • As an event-driven, non-blocking I/O model, each function is asynchronous. Finally, Libuv, a C/C++ event loop library, processes these I/O operations. It hides the nuts and bolts of non-blocking I/O, simplifies the concurrent programming model, and makes it easy to write high-performance Web applications, so it’s lightweight and efficient
  • usenpmAs package manager, currentlynpmIt is the largest ecology of package management in open source library with powerful functions. By December 2017, the number of modules has exceeded 600,000 +

Most people think node.js can only write backend or front-end tools, which is not comprehensive, Node.js aims to make concurrent programming easier, mainly used in network programming I/O intensive applications. Node.js is open source, cross-platform, and efficient (especially for I/O). IBM, Microsoft, Yahoo, SAP, PayPal, Wal-Mart, and GoDaddy are all node.js users.

1.1.3.c) Basic principles

The following is an early sketch of node.js architecture from a presentation by Ryan Dahl, the creator of Node.js, which is still out of date today, briefly explains that Node.js was built on Chrome V8. The Event Loop dispatches I/O tasks, and eventually the Work Thread drops them off to the Thread Pool. The Event Loop waits for the result.

The core concept

  • Chrome V8 is an open source JavaScript engine published by Google, written in C/C++ChromeIs used in the browser. The Chrome V8 engine can run independently or be embedded into C/C++ applications for execution.
  • Event Loop Indicates the Event LooplibuvProvide)
  • Thread Pool Specifies the Thread PoollibuvProvide)

comb

  • Chrome V8 is a JavaScript engine
  • Node.js has the Chrome V8 engine built in, so it uses JavaScript syntax
  • One of the hallmarks of the JavaScript language is single-threaded, which means you can only do one thing at a time
  • Single threading means that all tasks need to be queued until the first one is finished before the next one can be executed. If the first task takes a long time, the second task has to wait forever.
  • If the queue is due to a large amount of computation, the CPU is too busy to come over, but many times the CPU is idle, because I/O is very slow, have to wait for the result, and then proceed
  • The CPU can suspend the waiting task and run the next task, regardless of the I/O device
  • Place the waiting I/O task in the Event Loop
  • The Event Loop puts I/O tasks into the thread pool
  • Do what you can with the resources

Let’s look at it in another dimension

The core

  • Chrome V8 interprets and executes JavaScript code (which is why browsers can execute JavaScript)
  • libuvIt consists of an event loop and a thread pool, responsible for the distribution and execution of all I/O tasks

When it comes to concurrency, asynchrony is the best solution, and can be understood in terms of queueing and dialing machines

  • Waiting in line: When you’re standing in line, there’s nothing you can do but wait
  • Calling machine: All you have to do is take the number first, and when it’s your turn, the system will tell you, and in the meantime, you can do whatever you want

Node.js essentially helps us build a similar mechanism. When we write code, we are actually taking the number, which is handled by the Event Loop, and the actual operation is performed by the I/O task in the specific thread pool. Node.js is single threaded because it is single threaded when accepting tasks. It is very efficient without the cost of process/thread context switching, but it is multithreaded when performing specific tasks.

Node.js’ stated goal is “to provide an easy way to build scalable network applications,” and it certainly does. This approach simplifies the concurrent programming model, wrapping details such as Event loops and specific thread pools in Node.js, and exposing the asynchronous invocation Api to developers. On the one hand, it simplifies concurrent programming, on the other hand, it fosters the curse of writing. The benefit of this approach is that more people can easily write high-performance programs!

The node.js Bindings layer translates exposed C/C++ interfaces like Chrome V8 into JavaScript apis, and combines these apis to write the Node.js standard library. All these apis are collectively called the Node.js SDK. This will be discussed in more detail in a later module section.

Microsoft announced the opening of the Chakra engine under an MIT license in 2016 and made the source available on Github under the name ChakraCore, a complete JavaScript virtual machine, It has almost the same functions and features as the Chakra. Microsoft submits a code merge request to the main branch of Node.js to enable node.js to use the ChakraCore engine, the NodeJS/Node-Chakracore project. In fact, Microsoft gave ChakraCore the ability to handle Google’s Chrome V8 engine commands by creating a library called V8 Shim

Currently, Node.js supports both JavaScript engines, and both have different performance and features. ChakraCore is a bit more popular in terms of features. It was the first Async engine, but node.js is still dominated by Chrome V8. The ChakraCore version needs to be installed separately, so it’s good to know.

1.2. Part 1 Introduction: Learn the three states of Node.js

I’ve summarized the three realms of programming

  • Log: console.log
  • Breakpoint debugging: breakpoint debugging: node debugger or node inspector or vscode
  • Test-driven development (TDD | BDD)

You can test yourself. What level are you at? If it’s stage 3, then this Live may not be for you. Ha, ha, ha

1.3. Part 2 Preparation: How to learn Node.js

Node is not a language, it is not a framework, it is based on the V8 runtime environment. With Libuv you can achieve better C/C ++ equivalent performance through JS syntax.

It’s simple, asynchrony is a best practice for dealing with concurrency. This section is mainly about how to learn Node.js. It is the core content of this Live.

1.3.1. Basic learning

1) JS syntax must be able to

  1. Js basic syntax, are c language, have other language background to learn relatively easy
  2. Common uses such as re, data structures, and especially arrays. Such as bind/call/apply and so on
  3. Object-oriented writing. Js is object-based, so its OO is very weird to write. See Redbook for JavaScript Advanced Programming. Many frameworks implement oo basic frameworks themselves, such as Ext-Core.

Read the Rhino Book, the Definitive JavaScript Guide, as often as you can.

2) Personal learning and technology selection should be progressive

  1. If you can write it, you can write it procedurally, and you can define a bunch of functions, and then call them, very simple
  2. And then we can go for a better way of writing it, which is object-oriented. Oo has its advantages for large-scale programming, generally Java, c#, ruby and other languages have object-oriented, so the back end is more accustomed to, but for the front-end is not so strong language experience is advanced skills.
  3. When oo gets tired, you can move on to something better: functional programming, both in terms of programming thinking and usage, is a challenge to established programming thinking. I’m a big fan of functions, but I don’t really use them in a team because I haven’t fully mastered them in the OO stage and it’s risky. But if the team level is very high, team stability can be used.

So you can see where I’m going, first I can write, and then I’ll go for something better, like object oriented. When the team is at a certain level and stable, you can consider more extreme functional writing.

Team selection is like this, so is individual learning, it is best to step by step, a big step is not good.

3) Various high-level javascript-friendly languages

Javascript-friendly languages are those that can be implemented using other syntax, but are eventually compiled into JS. Since the advent of Node.js, this kind of dark technology has been popping up a lot. Coffee, typescript, Babel (ES), etc.

CoffeeScript is a javascript-friendly language, but its syntax is based on Ruby, it advocates minimalism, and it is still weak in terms of types and OO mechanisms. It has not developed over the years and is still relatively niche. There will be fewer and fewer in the future.

It’s clear that TypeScript will get better and better. You have to use TypeScript to know how powerful it is.

  • 1) Scale programming, Java like, statically typed, object-oriented, with a front end that only TypeScript can do
  • 2) His biological father is Microsoft Anders Hejlsberg. If you don’t know him, read the Legend of Borland
  • 3) Open source, the future is good
  • 4) TypeScript + VSCode = magic

The current front end is growing at an exponential rate. Where once there might not be a new technology a year, now there might be a new technology every month. Big front ends, Node stacks, architecture evolutions, and more are all changing fast. Arguably, the more complex and uncertain the front end, the better TypeScript’s chances.

4) Object-oriented again

Object-oriented want to use good is not easy, and THERE are various implementations of JS, is really dazzling.

  • Prototyping, if you look at JavaScript advanced programming, and you go back and forth on this, it’s pretty basic, but it’s not very useful. You don’t have to, but you don’t have to.
  • Writing your own object-oriented mechanics is best, but not everyone can do it. The good news is that the ES6 specification has a slightly better object-oriented approach, with classes defined through the class, extends, and super keywords, which are still weak, but at least marginally usable. For those of you who have come from a process orientation, this is recommended, it’s easy to use. However, we should pay attention to the object-oriented writing method and understand the four basic characteristics of abstraction, inheritance, encapsulation and polymorphism. You may even need to read books on design patterns if you want to use them well. Fortunately, there is a book called JavaScript Design Patterns. Koa2 already wrote it this way.
  • Js is a scripting language that can be interpreted and executed. So the biggest disadvantage is that there is no type system, which is very dangerous in scale programming, a function, passing parameters can play dead. So it’s popular to use Flow and typescript for type validation. Flow is just a tool. It’s lightweight. Typescript is an ES6 superset that complements ES6 with a type system and a more sophisticated object-oriented mechanism, so most people will like TS and it’s likely the future.

For ES6 advanced features, I am relatively conservative, general Node long-term support version LTS support I let use, some newer features I generally do not let use. Just keep the LTS version the same.

My team is currently developing in es6 object-oriented writing and will gradually move to typescript. The transition from skilled OO to TS is very easy.

1.3.2. Install the Node.js environment

3 m installation method

  • Node Version Manager (NVM) [Install using NPM, substitute yRM (support YARN)]
  • Node Registry Manager (NRM) [Install using NPM, alternative is YRM (support YARN)]
  • NPM (Node Packages Manager) [built-in, alternative is N or NVS (also supported for WIN)]

1.3.2.1. NVM

Node releases are quick and multiple versions are likely to coexist. NVM is recommended for node installation

$curl - o - https://raw.githubusercontent.com/creationix/nvm/v0.33.6/install.sh | bash $echo 'export NVM_DIR="$HOME/.nvm"' >> ~/.zshrc $ echo '[ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh" # This loads nvm' >> ~/.zshrc ZSHRC $NVM install 0.10 $NVM install 4 $NVM install 6 $NVM install 8Copy the code

1.3.2.2. NRM

Registry.npmjs.com is the official Registry of Node. The server is located in foreign countries and the download speed is slow. It is recommended to install NRM to switch the source.

$ npm install --global nrm --registry=https://registry.npm.taobao.org
$ nrm use cnpm
Copy the code

1.3.2.3. NPM

After NRM switches source, you can install NPM modules faster.

$ npm install --global yarn
Copy the code

NPM basic commands

The name of the describe shorthand
npm install xxx Install the XXX module but do not record it in package.json npm i xxx
npm install –save xxx Install the XXX module and record it in package.json. The dependency corresponding to the field is the module that the production environment must depend on npm i -s xxx
npm install –save-dev xxx Json. Dev-dependency (mocha, Chai, Sinon, Zombie, supertest, etc.) is a module that the development environment must depend on npm i -D xxx
npm install –global xxx The XXX module is installed globally, but not recorded in package.json. If there is bin configuration in package.json in the module, it will be automatically linked as a CLI command npm i -g xxx

1.3.3. Commonly used software

  • 1) OH my ZSH is the shell I am most used to. It is very easy to use in terminal

With iterm2 split screen + Spectacle full screen, almost invincible

  • 2) Brew is a very good way to install software on MAC, which is very similar to apt-get, RPM, etc

Install the four required software

  • Brew install Git is the most popular source control software for SCM
  • Brew install wget
  • Brew Install ACK search code artifact
  • Brew install Autojump for multiple directories

  • 3) vim

I may not be a Vim, but I love it. Janus is a very useful VIm integrated development environment. Plugins like CtrL-P, NerdTree, etc are integrated, which is enough for lazy people like me.

1.3.4. IDE and editor

There are a number of IDE and editor options for Node.js, compared to the following

The name of the Whether the charge Breakpoint debugging function
Webstorm charge support Is IDE, in the code hint, reconstruction and other aspects of the function is very powerful, support a variety of languages, frameworks, templates are also very much, support breakpoint debugging, the advantage is special intelligence, the disadvantage is also special intelligence
Sublime/TextMate charge Does not support Textmate is aimed at MAC users, sublime is cross-platform and will be familiar to many front-end developers
Vim/Emacs free Does not support The command-line editor is very powerful and slightly more difficult, but much cooler, and worth learning for server deployment development
VSCode/Atom free support Atom is early and powerful, but it has some drawbacks. VSCode is developed by Microsoft. It is fast and supports node.js debugging, refactoring, code prompting and other aspects very well

Visual Studio Code is a cross-platform source editor for writing modern Web and cloud applications that runs on Mac, Windows, and Linux. It’s powerful, easy to debug, and it’s built on the Electron module of Node.js.

Visual Studio Code (VSC)

  • VSC is a new editor (cross-platform Mac OS X, Windows and Linux)
  • VSC features compare favorably with textmate, sublime, notepad++, ultraedit, etc
  • VSC support is especially good on NodeJS (debugging) and typescript and Go
  • The VSC provides a custom Debugger Adapter and VSCode Debug Protocol to implement its own Debugger

Worth learning, I recommend VSCode editor!

For more debugging methods, see github.com/i5ting/node…

1.3.5.Node.js Application scenario

According to the book Node.js in Action, the application node.js targets has a special abbreviation: DIRT. It stands for data-intensive real-time program. Because Node.js itself is very lightweight in TERMS of I/O, it’s good at shugging or proxying data from one pipe to another, which holds a lot of open connections while processing a lot of requests, and takes up a small amount of memory. It’s designed to be responsive, just like a browser.

That’s true, but DIRT is small today. DIRT is basically all about I/O, but with the development of the big front-end, Node.js is no longer just about I/O, it’s more “Node”!

Node.js usage scenarios are divided into four categories

  • 1) Cross-platform: cover all user-facing platforms you can think of, traditional PC Web, and PC clientsnw.js/electron, mobile terminalcordova, HTML 5,react-native,weexThe hardwareruff.io
  • 2) Web application development: website, Api, RPC service, etc
  • 3) Front end: Three frameworks React \Vue \ AngularAssist in development, and engineering the evolution process (useGulp/Webpack build Web development tools)
  • 4) Tools:npmOn a variety of tools module, including a variety of front-end precompilation, build toolsGrunt / GulpScaffolding, command line tools, all kinds of clever tricks

The specific Node.js usage scenarios are listed below, broken down by module dimensions

classification describe Related modules
Web site Similar to thecnodejs.orgSuch a traditional website Express / Koa
Api Also available on mobile, PC,H5Such as front-end useHTTP Apiinterface Restify / HApi
Api agent For the front-end, the main back-end Api interface for reprocessing, in order to adapt to more front-end development Express / Koa
IM Instant Chat Real-time applications, a lot of them are based onWebSocketOf the agreement Socket.io / sockjs
The reverse proxy Provide something similar tonginxReverse proxy features, but is more front-end friendly anyproxy / node-http-proxy / hiproxy
Front-end build tools Assisting front-end development, especially all kinds of pre-compilation and building related tools, can greatly improve the efficiency of front-end development Grunt / Gulp / Bower / Webpack / Fis3 / YKit
Command line tool Using the command line is a cool way to do it. Front-end development has a lot of custom tools, whether it’s shell commands, Node scripts, or various scaffolders, almost every company/group has its own set of command-line tools Cordova / Shell.js
The operating system There are implementations, but they’re not likely to be used NodeOS
Cross-platform packaging tool Using Web development technology to develop PC clients is the most popular way at present, and more front-end development tools will adopt this way Electron, NNW. Js on PC, such as Dingding PC client, wechat mini program IDE, wechat client, mobile Cordova, the old Phonegap, and the more famous one-stop development framework Ion Framework
P2P Blockchain development, BT client webtorrent / ipfs
The editor AtomVSCodeAre based onelectronThe module electron
Internet of Things and hardware Ruff. IO and many hardware devices support the Node SDK ruff

Node.js has a lot of application scenarios. For example, Node.js can be used to develop operating systems, but I don’t talk about it. Even if I do, it doesn’t mean much. In general, I tend to divide the Node.js application scenario into seven parts.

2) Command line assistance tools, even o&M. 3) Mobile: Cordova, PC: Nw. js and ELECTRON 4) componentalization, construction, proxy 5) architecture, front-end and back-end separation, API Proxy 6) performance optimization, anti-crawler and crawler 7) the most convenient way to full stack

Serial number scenario instructions
1 The reverse proxy Node.js can act as a reverse proxy for Nginx, which we rarely do online, but it does. For example, node-HTTP-proxy and AnyProxy, in fact, using Node.js to do this request forwarding is very simple, in the HTTP section later, there is a separate explanation.
2 The crawler There are a number of crawler modules, such as Node-Crawler, that are easier to write than Python, especially with jsDOM (the Node version of jQuery) libraries, which are particularly front-end friendly
3 Command line tool All auxiliary development, operation and maintenance, improve efficiency and so on can be done by cli, using Node to develop are very suitable, is the simplest way to write command line tools, Java8 after reference to the command line implementation of Node
4 Microservices and RPC Node has a variety of RPC support, such as DNode written by Node, Seneca, and cross-language support for GRPC, enough to apply
5 Development of wechat official account Related SDK, framework is very many, is the weapon of rapid development
6 Front end popular SSR && PWA SSR (server-side rendering) and PWA (progressive Web application) are the hottest technologies this year. If you’ve used node.js, you’re familiar with it. React and Vuejs, for example, are SSR implementations of Node.js. The pWA service-worker is also implemented in Node.js. So why not implement it in another language? It’s not that other languages can’t do it, but node.js is simple, convenient, cheap to learn, and easy to get high performance. If I were using another language, I’d at least have to install the environment

It can be said that all the software you can see and use at present has Node.js. Most of the most popular software writing methods are based on Node.js, such as PC client Luin/Medis using electron packaging and React + Redux. My own practice of “Node full stack” is based on this trend. In the future, Node.js will be used in a wider range of scenarios, see sindresorhus/awesome-nodejs for more.

1.3.6. Node core: Asynchronous process control

Node.js was built for asynchrony, and it does the complicated work itself (high concurrency, low latency), leaving the user with a slightly difficult Callback script. It is also the open exposure of asynchronous callbacks that leads to better process control evolution. It is these evolutions that have allowed Node.js to expand from DIRT to a wider range of applications. Today, Node.js is not only capable of writing back-end JavaScript, it covers all aspects of development, and the full Node stack is a popular category.

Facing the problem directly can have a better solution, node.js asynchrony is the most important in the whole process of learning Node.js.

  • 1) Learning focus of asynchronous process control
  • 2) Api writing: Error-first Callback and EventEmitter
  • 3) Promise
  • 4) Ultimate solution: Async/Await

1.3.6.1.1) Learning focus of asynchronous process control

I’ve put together a picture that’s a little bit more intuitive. In the 8 + years between 2009 and now, the entire Node.js community has done a lot of experimenting, with enough twists and turns to fill a book. So let me give you a quick overview.

  • Red represents Promise, which is the most used, and is available to both Async and Generator
  • Blue is Generator, out of stock
  • Green is Async function, trend

Conclusion: Promise is a must, so why don’t you go with the flow?

Recommendation: Use the Async function + Promise combination, as shown below.

In fact, it is not necessary to master all the techniques shown above. For beginners, enough first, then go into the details. So, to simplify, just knowing three is enough.

conclusion

  1. The node.js SDK has to write callback.
  2. Node.js focuses on Async functions and Promises
    1. Mainstay: Promise
    2. Ultimate solution: Async/Await

So we’ll break it down into small sections.

1.3.6.2.2) Api writing: Error-first Callback and EventEmitter

A) error-first Callback defines an error-first Callback by following only two rules:

  • The error object returned by the first argument to the callback function. If an error occurs, it is returned as the first err argument. If not, it is common practice to return NULL.
  • The second argument to the callback function returns the result data of any successful response. If the result is normal and no errors occur, err is set to null and the second argument returns success data.

Let’s take a look at an example of calling a function. Node.js documentation most often uses the following callback method:

function(err, res) {
  // process the error and result
}
Copy the code

Callback here refers to a function with two arguments: “err” and “res”. Semantically, a non-empty “ERR” is equivalent to a program exception; The empty “err” indicates that the result “RES” can be returned normally without any exception.

B) EventEmitter

The event module is a built-in Node.js implementation of the “Publish /subscribe” observer pattern, providing a constructor via the EventEmitter property. An instance of this constructor has an on method that can be used to listen for the specified event and trigger the callback function. Any object can post events that are listened to by the On method of the EventEmitter instance.

After Node 6, you can use the require(‘events’) class directly

var EventEmitter = require('events') var util = require('util') var MyEmitter = function () { } util.inherits(MyEmitter,  EventEmitter) const myEmitter = new MyEmitter(); myEmitter.on('event', (a, b) => { console.log(a, b, this); // Prints: a b {} }); myEmitter.emit('event', 'a', 'b');Copy the code

Very similar to Event in jquery and Vue. And the front end has EventEmitter of its own.

C) How to better view node.js documents

API is short for Application Programming Interface. Node.js is called by the API in the Node.js SDK, which is then executed by the EventLoop (Libuv), so we must be familiar with node.js API operations.

Node.js API is asynchronous, synchronous functions are not required, please check the API documentation, use caution in high concurrency scenarios.

I recommend using Dash or Zeal to view offline documentation. Checking offline documentation often gives you a much deeper understanding of the Api than IDE assistance and prevents you from writing code without leaving the IDE.

1.3.6.3.3) Mainstay: Promise

The callback hell

Node.js uses the error-first callback style, resulting in all SDK exports being callback functions. This is especially painful when combined calls are often nested within callbacks, and people get tired of writing this method called Callback Hell. A classic example comes from the famous Promise module Q documentation.

step1(function (value1) {
    step2(value1, function(value2) {
        step3(value2, function(value3) {
            step4(value3, function(value4) {
                // Do something with value4
            });
        });
    });
});
Copy the code

This is just 4 steps, 4 layers of nested callbacks. What if there are more steps? Many novice dabble, here on the back of the powder turned black. This is obviously immature, at least you should see the solution!

Node.js convention all apis use error-first callback, this part of the scenario is people directly call the interface, not much change. And Promise is a reflection on callback hell, or refinement. At present, it is widely used, which can be said to be the only universal specification before the popularization of async function. Even the Node.js community is considering Promise, which shows its great influence.

Promise was also first introduced in the CommonJS community, where a number of specifications were proposed. The more accepted is the Promise /A specification. People built on that with the Promise /A+ specification, which is actually what the industry is pushing today. ES6 also uses this specification.

Promise means [| promised vows] a haven’t finished the operation, but in the future to be completed. The primary way to interact with a Promise is by passing a function into its then method to get the final value of the Promise or why the Promise ultimately rejects it. There are three main points:

  • Recursively, each asynchronous operation returns a Promise object
  • State machine: Three state transitions that can only be controlled inside the Promise object and cannot be changed externally
  • Global exception handling

1) define

Var promise = new promise (function(resolve, reject) {// do a thing, then... if (/* everything turned out fine */) { resolve("Stuff worked!" ); } else { reject(Error("It broke")); }});Copy the code

Each Promise definition is the same, passing in an anonymous function in the constructor that takes resolve and reject, which represent success and failure, respectively.

2) call

promise.then(function(text){ console.log(text)// Stuff worked! Return promise.reject (new Error(' I did it intentionally '))}). Catch (function(err){console.log(err)})Copy the code

Its primary interaction is through the THEN function, and if a Promise successfully executes resolve, it passes the value of resolve to the nearest THEN function as an argument to its THEN function. If something is wrong, reject, then you just pass it up to catch.

Promise’s biggest advantage is standardization. All asynchronous libraries are implemented according to a uniform specification, and even async functions can be seamlessly integrated. Therefore, USING Promise to encapsulate API is universal, easy to use and low cost to learn. Before the popularization of async function, most applications use Promise to do asynchronous flow control, so mastering Promise is the top priority that must be mastered in the learning process of Node.js.

Bluebird is the best performance in the node.js world Promise/ A + specification implementation module, Api is very complete, powerful, is the original Promise outside the choice.

The benefits are as follows:

  • Avoid node.js built-in Promise implementation issues and use compatible with all versions
  • Avoid the memory leak that occurred in Node.js 4
  • Built-in extensions such as Timeout, promisifyAll, etc. complement the Promise/A+ specification

Again, it’s not too much to learn about Promise as you learn Node.js.

Recommended learning materials

  • The Promise of node.js latest technology stack cnodejs.org/topic/560db…
  • Understand how Promise works cnodejs.org/topic/569c8…
  • Promise the mini book liubin. Making. IO/promises – bo…

1.3.6.4.4) Ultimate solution: Async/Await

Async/Await is the ultimate solution for asynchronous operations. Koa 2 was released immediately after Node 7.6 was released, and it is recommended to write Koa middleware using Async functions.

Here is a snippet of code from a Koa 2 application

exports.list = async (ctx, next) => { try { let students = await Student.getAllAsync(); await ctx.render('students/index', { students : students }) } catch (err) { return ctx.api_error(err); }};Copy the code

It does three things

  • Through await Student. GetAllAsync (); To get all the students’ information.
  • Render the page with await ctx.render
  • Exception handling using try/catch because of synchronous code

Eggjs synchronizes code like this.

4.1 Normal writing

const pkgConf = require('pkg-conf');

async function main(){
    const config = await pkgConf('unicorn');

    console.log(config.rainbow);
    //=> true
}

main();
Copy the code

Abnormal writing

const pkgConf = require('pkg-conf');

(async () => {
    const config = await pkgConf('unicorn');

    console.log(config.rainbow);
    //=> true
})();
Copy the code

4.2 await + Promise

const Promise = require('bluebird');
const fs = Promise.promisifyAll(require("fs"));

async function main(){
    const contents = await fs.readFileAsync("myfile.js", "utf8")
    console.log(contents);
}

main();
Copy the code

4.3 await + co + generator

const co = require('co');
const Promise = require('bluebird');
const fs = Promise.promisifyAll(require("fs"));

async function main(){
   const contents = co(function* () {
      var result = yield fs.readFileAsync("myfile.js", "utf8")
      return result;
   })

    console.log(contents);
}

main();
Copy the code

The main points of

  • The return value of co is a promise, so await can be used directly with CO.
  • The co parameter is genrator
  • Yield is available in a generator and is yieldable for five possible purposes.
    • Promises
    • Thunks (functions)
    • array (parallel execution)
    • objects (parallel execution)
    • Generators and GeneratorFunctions

The main points of Async function can be deduced from the above 3 basic usages as follows:

  • Async functions are semantically very good
  • Async does not require an executor and is capable of executing itself, unlike Generator which requires a CO module
  • Async functions use try/catch and Promise error handling, which is very powerful
  • Await Promise, Promise itself is enough to deal with all processes, including async function without pure parallel processing mechanism, can also use all and race in Promise to complement
  • The combinatorial ability of Await to release promises, plus the THEN of CO and Promise, has few scenarios that are not supported

From what has been discussed above

  • Async functions are the trend if Chrome 52.V8 5.1 already supports Async functions (github.com/nodejs/CTC/…) Is Node.js support far behind?
  • Both Async and Generator functions support promises, so promises are mandatory.
  • Generator and Yield are incredibly powerful, but won’t become mainstream, so it’s good to learn the basics and promise, not necessarily all of them.
  • Co is good as a Generator executor, but it’s even better as a Promise wrapper. Support yieldable via Generator and return promises.

summary

This section covers four small points, all of which are extremely straightforward and must be understood.

  • 1) Learning focus of asynchronous process control
  • 2) Api writing: Error-first Callback and EventEmitter
  • 3) Promise
  • 4) Ultimate solution: Async/Await

Here again about node.js source code reading problem, many people API is not playing skilled to read the source code, this is very disapproved of, not with the problem to read the source code is easier to get lost in a lot of code. It didn’t work out well.

Then read the Node.js source code and explore the libuv concurrency mechanism. A lot of people bought Pu Da’s “simple Node.js” book, after reading or not very good use, not writing bad, but the wrong steps.

  • Node in Action and the awesome Node.js are great books to get started with. They are very simple, cover all the parts, but don’t go into too much depth
  • After you’ve used it for a while, you’ll wonder how Node.js works. Why? At this time to read Park’s “simple Node.js” book can be solved. The reason is very simple, nine shallow a deep book is biased to the underlying implementation of the principle of the book, from the operating system, concurrency principle, Node source layer interpretation. If it is a novice reading, unavoidably will be more depressed.
  • For practical classes, you can see the books written by lei zongmin (Lao lei) and zhao kun (NSWBMW)

My general recommendation is to read Node in Action five or ten times. Getting started is enough. The rest is a matter of trial and error, writing lots of code and NPM modules.

Almost all of the current books are a bit out of date, most of them are around Node.js V0.10, and my new book is based on Node.js 8, due out in March/April 2018. Don’t rush me. It can’t go any faster.

directory

  • 01 Node. Js first
  • 02 Installation and Getting Started
  • 03 More awesome Node.js
  • 04 Better Node.js
  • How is Node.js executed
  • Module and core
  • 07 Asynchronous writing and flow control
  • 08 Getting started with Koa, the next generation Web Framework
  • Koa’s core extension mechanism: middleware
  • The HTTP protocol must be known and must be known
  • 11 Koa practice
  • 12 Getting Started
  • 13 Database Advanced
  • 14 View Templates
  • 15 Koa project actual combat
  • 16 Write the NPM module by yourself
  • 17 Node.js enterprise-level Web development
  • 18 Build microservices with Node.js features
  • 19 Makes Node.js run more smoothly
  • 20 makes Node.js run faster

The beauty editor of the point of view of the blog is in helpless and painful arrangement, it is expected to be published in March, 20 chapters, 800 + pages, the price is expected to be 130+.

1.3.7. Web programming essentials

In general, back-end development refers to the part of Web application development that has nothing to do with view rendering. It is mainly business-heavy logic processing that mainly interacts with databases. But now that the architecture has been upgraded and Node.js has taken on the burden of separating the front and back ends, there’s a lot more to play with. From the traditional Web application with view and apI-oriented interface application, to the operation of database encapsulated through RPC call, to provide front-end Api proxy and gateway, service assembly, etc., collectively referred to as back-end development, is no longer only the part that deals with database. In this way, front-end engineers can control the development process, better tuning and performance optimization.

For Node.js, the backend has never achieved its fair share for a number of reasons, just to name a few.

  • 1) Profit distribution, the existing implementation is mostly Java or other languages, is basically unshakeable, rewrite the cost is huge, in addition, if written in Node, then what about those who write Java? You have to fight for your bread and butter.
  • 2) Node is relatively young, people do not understand Node well, callback and asynchronous flow control is a bit troublesome, many architects do not want to spend time to learn. Although it is very simple and efficient to deal with in the Web application part, it is not easy to troubleshoot and locate problems, requiring slightly higher level of developers.
  • 3) Developers have single skills, many of which are transferred from the front end, and lack knowledge of database and architecture, as well as system design, which is very dangerous and makes them feel afraid to fight the Wolf at both ends.
  • 4) Node does not do well in science popularization, training, preaching and other aspects. It is widely used abroad, but few people in China know it. It is not as good as some languages.

Still, Node.js is known for being caught up in all sorts of controversies, and for being a big front-end hit. The reason is that it is very clearly positioned to complement the server part of the full stack architecture with JavaScript at its core. Development is also human, and there are not many people who can master and master multiple languages at the same time. Besides, the virtue of programmers is “lazy”. Why should they learn more when they can use JavaScript to do everything in one language?

There are roughly two types of Web applications, traditional Web applications with views and API-oriented applications. Let’s first take a look at the evolution timeline of Node.js Web application development framework as follows:

  • Express by TJ Holowaychuk in 2010
  • Derby.js development began in 2011, and on August 5, Eran Hammer, a member of WalmartLabs, submitted Hapi’s first Git record. Hapi was originally part of Postmile and was originally built on Express. It later evolved into its own framework,
  • On January 21, 2012, Restify, which focuses on the Rest API, released version 1.0, and isomorphic Meteor started development, along with the most Rails-like Sails
  • In 2013 TJ Holowaychuk started playing es6 Generator and writingcoThis Generator executes and starts the Koa project. In the second half of 2013, Li Chengyin started ThinkJS, referring to ThinkPHP
  • On April 9, 2014, Express released 4.0 and entered the 4.x era. The development of Mean.js began with the proposal of MEAN architecture, with the intention of unification. In addition, Total. Frameworks that are most like Laravel in PHP or Django in Python or ASP.NET MVC represent the maturity of node.js and begin to borrow from mature frameworks in other languages
  • On August 22, 2015, Koa, the next generation Web framework, released 1.0, available under Node.js v0.12, throughcoImplement synchronization logic with generator at that timecoAre based onthunkfyOn October 30, 2015, ThinkJS released the first V2.0 version based on Es2015+ features
  • In September 2016, Ant Financial’s Eggjs was unveiled at JSConf China 2016 and announced open source
  • In February 2017, Koa, the next generation Web framework, released v2.0

We can classify frameworks according to their characteristics

Name of the framework features review
Express Simple, practical, routing middleware and other five viscera The most famous Web framework
Derby.js && Meteor homogeneous The front and back ends are put together, blurring the ease of development, making it look simpler, but actually more demanding for development
Sails, Total For other languages, Ruby, PHP, etc Drawing on the best implementations in the industry is also a sign of Node.js maturity
MEAN.js Oriented architecture It’s like scaffolding, expecting isomorphism, and it just bumps the hot spot
Hapi and Restfy Api && microservices oriented In the era of mobile Internet, the role of Api has been enlarged, so it is classified independently. Especially for microservices development is a great tool
ThinkJS New feature oriented Learn from ThinkPHP, and slowly out of their own way, for Async functions and other new features support, no better, the new version of V3.0 is based on Koa V2.0 as the kernel
Koa Focus on asynchronous process improvement Next Generation Web Framework
Egg Based on Koa, there is great convenience in development Enterprise Web development framework

For frame selection

  • Business scenarios, characteristics, not for the sake of what, avoid putting the cart before the horse
  • Sometimes, the team atmosphere is determined by its own team capabilities and preferences, and the selection of technology, so it needs to balance radicalism and stability
  • When something goes wrong, someone can do source-level customization. Node.js has a history of 8 years, but the module is not perfect, if accidentally stepped on a pit, the team needs to be able to solve the situation without external force, otherwise it will affect the progress

Tips: Personal learning for innovation, enterprise architecture for stability, nothing more than preferences and scenarios

Node.js was originally designed to be a backend, so let’s look at the benefits here. The extension of Node.js to the back end is bound to touch the interests of back-end development. So the Proxy layer, the intersection of the conflict between the front end and the back end, the back end does not want to change, and the front end wants to change, so long as this goes on, the Api interface will become more and more disgusting. The back end is willing to call the Api thing the front end, as long as you don’t touch my database and services.

But can Node.js do this? The answer is yes, this is similar to Java, PHP, and generally connected to the database, processing with business logic. It is not easy to get access to Java and PHP, which are the main products in Korea.

  • Small companies, startups, and newly hatched projects prefer Node.js, which is simple, fast, and efficient
  • It makes sense to use Node.js for some services under the microservices architecture

This part has not been well done in China, so Node.js has not been well applied in large companies, such as security problems, ecological problems, historical problems, and many people’s misunderstanding of Node.js.

  • It’s true that a single thread is vulnerable, but a single thread doesn’t mean you can’t have multi-core concurrency, and you still have clusters
  • Operation and maintenance is actually very simple, simpler than other languages, log collection, monitoring is also very simple
  • Module stability, forMongoDB,MySQL,RedisEtc is still pretty good, but other database support may not be so good.
  • Security is a false proposition, and all frameworks are the same.

This is enough to provide Api services, and there is a lot later in this book about how to build Api services using the Koa framework.

Web Programming Core

  • Asynchronous process control (described earlier)
  • Basic framework Koa or Express, beginners recommend Express, after all, more information, easier to get started. Koa is recommended if you have some experience, but this is all about understanding Web programming principles, especially middleware mechanisms.
  • Mongoose and Sequelize, Bookshelf, TypeOrm, etc are all very good. For transactions, it’s not node.js’s pot, it’s the database you choose. Some other partial door, want node to connect sqlserver and so on estimate is not mature, I will not use it.
  • Template engines, EJS, Jade, Nunjucks. The principle is best understood. Especially extend, include and other advanced usage, understanding layout, reuse benefits. It’s the same idea at the front and back ends.

1.3.8. The best way to learn Node.js when confused

Node.js package manager NPM has become the best ecosystem of open source package management in the field. As of October 2017, there are more than 470,000 modules, more than 3.2 billion downloads per week, and more than 7 million developers use NPM every month. There are now more than 600,000 modules.

Here’s a list of the best ways to learn Node.js when you’re confused.

One day, I was sorting out manuscripts at 3W Coffee, and my younger brother Liang came over to talk about his current situation, which was very bad. I had taken him under my guidance for more than half a year in Tianjin, but I couldn’t ignore him. My advice to him was: “Look at 10 NPM modules every day”.

This is the best way for people who are confused about learning Node.js to move forward when you don’t know what to do, and you need to know which skills will benefit you later. The only way to learn Node.js is to master a lot of module usage and learn skills, ideas and design ideas from it. Instead of not knowing what to learn, why not accumulate a few skills every day?

A recommended repo is github.com/parro-it/aw… Small library collection, a day to see ten is not a dream!

More discussion zhuanlan.zhihu.com/p/29625882

1.3.9. How about node.js without a degree

I have a question from a friend

Uncle Wolf, I have been paying attention to you and Cnode for a long time. I am a little confused recently. I would like to ask you for advice. My situation is as follows. I have been engaged in front-end work for 4 years without any academic training. The technology stack used by the company is VUE2, VUE-Router, VUex and Webpack. Weaknesses: 1. Non-academic background, weak computer foundation; 2. Lack of in-depth understanding of current technology, many things only stay at the level of use; 3Copy the code

Answer the puzzle:

1, weak computer foundation how to improve their knowledge system?

A: Chase the long tail, what you see and hear don’t understand to learn. I did this for the first few years, 14 hours a day +, very tired, but the effect is ok. OS, algorithms, data structures, design patterns, compilation principles, that’s basically it. Just make progress every day, don’t expect too much. Math and English of course is also the more ruthless the better!

2. How to make further exploration in technology?

A: Tech people focus only on technology and usually have few ideas. The easiest way to do this is to scratch myself. I’ve translated Grails documents with my friends in college, so I have a lot of interest in translation. For translation purposes, I have written numerous tool trials with Node, comparing various translation tools repeatedly and understanding the design behind them. Include markdown embedded HTML tags to identify English and Chinese, and gulp compiles them into separate documents. Even once wanted to sell services online. This kind of torturing is really cool, even delayed a lot of translation. Sometimes be wary of the long tail and remember where you came from

3. How to systematically learn Node?

Answer: the phase

1/ Be able to use and get the job done 2/ write productivity tools 3/ Participate in open source projects, even Node source code

response

1/ Watch Node in Action five times and write it, regardless of the quality of the code. 2/ Use more modules, understand them, and write it yourself if you have a chance, in case a lot of people use you. My brother wrote json data for a locale selection load, and there are a lot of stars. To learn from others’ habits, git standard workflow and pr methods are available online. All you need to do is study the module code, pay attention to the issue, and wait for opportunities. In addition, Pu Ling’s simple to read a few times, try to read node source code, your understanding will be better. I recommend reading my book learning through Open Source Projects github.com/i5ting/Stud… 4/ Going beyond Node and re-examining node scenarios will help you with your future technology options and decisions

  • 2.1 Node has so many uses, where do I start?

A: If you have the opportunity, go straight to Web applications, if you don’t have the opportunity to start from the front end build, tools, etc., and gradually introduce cooler and cooler front end technology, which naturally leads to Node. Don’t worry.

  • 2.2 Node Web Framework so many, how should I choose?

A: Beginners recommend Express, and if you have some experience, Koa. Of course, Eggjs and Thinkjs frameworks are recommended for real projects.

  • 2.3 Books on Node are almost out of date. Which one should I buy?

A: 1) Node in Action and node. js are great books to get started with. They are very simple and cover all the parts, but don’t go into too much depth. At this time to read Park’s “simple Node.js” book can be solved. The reason is very simple, nine shallow a deep book is biased to the underlying implementation of the principle of the book, from the operating system, concurrency principle, Node source layer interpretation. If it is a novice reading, unavoidably will be more depressed. 3) for practical ones, read the books written by lei zongmin (Lao lei) and zhao kun (NSWBMW)

If you’re not in a hurry, you can also wait for my more Awesome Node.js, due in March next year.

1.4. Part 3 Extension: The big front end changes so fast, how can we achieve daily improvement?

Some friends ask which is the better prospect of Android development or Web front-end development? My answer is that the front end is obviously better, and look at how mobile is evolving

native < hybrid < rn/weex < h5

Rn and WEEX are becoming mainstream, and component-based writing is dominated by the front end. There used to be a high percentage of ios and Android programmers, but now there are only one or two writing plug-ins, which is a big difference.

Web development has a huge impact on mobile. Of course, now Web technology also developed PC client, such as VScode is packaged through electron, the effect is quite good.

The front end has been the hottest part of development in recent years, for a number of reasons, most notably a change in the way development is done.

Start with an overview of modern Web development

Every time I give a talk, I ask you if it’s the front end, and a lot of you say “yes”, and I jokingly congratulate you: “Front end” is money, indeed, rapid development of the front-end abnormal now, and there is no tendency to analogy that stability of SSH framework in Java, so in the future for a long time, will also increase, the continuing chaos, it is a double-edged sword for the front end, on the one hand have a thorough knowledge of the oppressive feeling, not learn to keep pace with times, on the other side it is also an opportunity, Can bring more opportunities, including money.

One of the questions that everyone is wondering about is how to learn to adapt in such a time of change. I can honestly say that there are no shortcuts, but mastering Node.js will help you reduce the learning curve, because node.js is a big front-end infrastructure. As you can see, the front-end development process, modularization, construction, accessibility, tuning, architecture tuning, you can say node.js is everywhere.

In fact, helping with big front-end development is a very unintended extension of Node.js, and by mastering Node.js you can do more, achieve more, and even have more self-fulfilling happiness, which is what the “Awesome” title of my book is all about.

In summary, this is why I have been advocating the concept of Node full stack with JavaScript as the center. JavaScript covers all the front ends, node.js is good at doing I/O intensive back ends, plus various infrastructure to assist development. It is undoubtedly the best way to work, learn and become a fast master of full stack technology. The more you learn, the more you can do, and the more wonderful chapters you will have in your life.

The whole stack core

  • Back-end UI not (interface dependent)
  • Front-end DB not (business related)

Once you get through these two key points, the rest will be easier. The worst thing you can do is call yourself a “full stack” and advise you not to do so. This is like saying “master” on your resume. Full stack is a kind of belief, not to brag, but can solve more problems, let their knowledge system leave no blank, enjoy the ultimate happiness of self-realization.

1.4.1. My way to the full stack

Wolf uncle’s recent business has always been a simple express to build a back-end service, there is no other deeper node business, this time how to create their own application scenarios

If you have no goals, look to the money. If you have goals, look forward

  • Started from Java, ceng class, carrying the case to Shenzhen, 3 months fat 20 catties
  • Keep translating English documents. See Thinking in Java.
  • I started BI after graduation and sorted out BI documents
  • Ming Linqing, the senior, teaches jQuery, willing to learn, others are more willing to share
  • Took over the “Inner Mongolia Radio and Television Data Analysis and Scientific Decision-making System” and opened the front and back ends
  • Guangdong Unicom, make your own wheels, write jQuery plug-in, DRY
  • Doing cloud computing, learning AIX, and writing “Transiting”
  • I broke up, quit my job, worked on iOS, started working on H5 from Cordova, studied various mobile framework, wrote my own framework, and switched to native
  • Interview is also a learning tool, easy into sina
  • I learned a lot about iOS, wanted to write a book, and ended up writing a bunch of tools for writing books

Since there is no escape, love it, and finally become interested

  • Go to net qin to be the technical director, be the chief, manage the architecture, lead people, write open source projects
  • Start a business, when CTO, get married, do the public number operation, write a book, the most bitter time no money to eat, and can not find a wife to want, can only speak some classes in StuQ
  • Join Qunar as a front-end architect
  • Join Alibaba, front-end technology expert

Life is more than a code, but it can make me happy, lifelong benefit

I have been ignorant and confused, but I am a silly person, always believe: “do one thing at a time, try to do the best”, in a short time it is silly, but once you stick to it, you will find that technology is actually a craft, thick accumulation of hair.

I can’t say what I’m good at, but I’m good at using what techniques in what situations. Or rather, it’s my greatest skill. I have never seen or used many frameworks and new technologies, but with a little bit of experience, I can take the existing knowledge and quickly understand it, which is actually the benefit of long-term learning.

Now I am busier and busier, I have less time to write code, and the technology is developing faster and faster. What I can do best is to improve myself every day and compete with young people with the knowledge I already have. I do not feel tired, on the contrary, I enjoy this feeling, not eliminated by The Times, is a happy thing.

1.4.2. Transfer from the back end

Be the guy on the back end

  • Be familiar with database, whether mongodb, mysql, postgres
  • Weak understanding of front-end, familiar with basic HTML, CSS, template engine, etc

Step by step, build and tool together

Front-end development phase 4, my feeling is in order, step by step good.

1.4.3. Switch from the front end

From front to back, APIS are very easy to learn. Frameworks like Express and KOA can be learned by most people in a week. The most difficult thing is to understand the DB and ER models, or to put it bluntly, to understand the business requirements

Let’s think about what the typical front-end skills are.

  • html
  • CSS (Compatible with Browsers)
  • Js (probably more jquery)
  • Ps cut figure
  • Firebug and Chrome Debuger are not popular
  • I’ve used a few frames, but most people just know how to use them
  • General English
  • SVN/git a little

So what are the challenges for them to get deeper into the front end?

  • Basics: OO, DP, commands, shell, build, etc
  • Understanding of programming ideas (MVC, IOC, protocol, etc.)
  • To distinguish the concept
  • Peripheral acceptance, such as H5 and Hybird
  • Catch up, how to learn new things

These are all pain points, so a better solution would be this.

  • Play with front-end utility classes like NPM and GULP (still front-end at this point)
  • Use Node for front and back separation (at this point, the front end)
  • Express, KOA, etc
  • Jade, EJS and other template engines
  • nginx
  • How to play the “back-end” asynchronous processes processing (promise/es6 (generator | yield)/es7 (async | await))
  • Play [back-end] mongodb, mysql corresponding Node module

From our experience, this is more reliable. First, do the simplest separation of front and back ends, which has nothing to do with DB. The front end can be very easy to learn, and you have been very skilled in 2 weeks. Generally, after half a year, let them contact [asynchronous process processing] and [database] related content, learn back-end code, can be full stack.

1.4.4. Transfer from mobile terminal

Take a look at the evolution of mobile

native < hybrid < rn/weex < h5

Rn and WEEX are becoming mainstream, and component-based writing is dominated by the front end. There used to be a high percentage of ios and Android programmers, but now there are only one or two writing plug-ins, which is a big difference. Wolf uncle has been stubborn to think that the future is H5.

Now the Native development is that grandma does not love uncle, very embarrassing, it is obvious that even the training of employment do not pay to mix experience is obvious. In addition, the leaders are also thinking about, can you write in H5? That’s conservative, because if you go straight to radical and you go straight to RN, then Native developers are different

A programmer who writes plug-ins… Who pissed off who…

Either endure, or turn, there is no way, accept fate, warm water comfortable for several years, also should learn something

  • Hybrid or componentized development, you always have to be the same
  • Either way, you’re close to the front end, because H5 or componentization comes out of the front end
  • Componentization takes the lead in the front-end domain, and it is inevitable to learn from it
  • If you don’t have time to go straight to componentization, if you do have time to learn about front-end integrity, and ultimately componentization

Native development is OC/Swift for iOS, Java or Scala for Android, etc. Even if webView is occasionally embedded, there is very little chance to play JS

The best way to move to full stack is to start with Cordova (formerly phoneGap) and do hybrid development.

  • Just pay attention to the WWW directory H5 can be relatively simple
  • If H5 is not enough, you can write a cordova plug-in that allows JS to invoke the native SDK functionality
  • The CLI of Cordova can be installed using NPM
  • Learn gulP build tools

Once you get into the H5 pit, it’s actually very easy to do.

  • Then h5, Zeptojs, iscroll, FastClick, etc
  • Vux (vue+ Weui), jMUI (React + Weui)
  • Then you can play with frameworks like jquery Mobile, Sencha Touch
  • Then you can play with the advanced ionicframework (angularjs, cordova).
  • Then the front end of 4 stages, in turn play strange upgrade
  • Then the node

This is basically a summary of the path I’ve taken since 2010, when I was writing iOS and working on PhoneGap (0.9.3 at the time).

In the past, the development of technology was not so obvious. When I was writing Java, Apache was used for open source. At that time, open-source code hosting sourceForge and Google Code were also used. Make a large number of star projects out of the lead. This is a good thing. Without open source, Chinese software would be years behind. So the question is, how can we improve our personal growth in today’s rapidly evolving technology?

There are three levels of learning. Learning from people is the fastest, followed by learning from books (or blogs), and the worst is self-realization. But cattle can not meet, met also may not have the energy to teach you, books or blogs, others have, but not necessarily write out, even if written, may just point to the end. As for self-realization, without profound accumulation, it is still quite difficult.

For the development of the code is all the basis, in the grasp of a certain computer foundation, the difference lies in the quality of the code and vision. There are no shortcuts to programming, and it’s great to be able to practice daily. Now open source code is very much, to be able to obtain the knowledge they need, is also a kind of ability! There is no need to learn from others if you can keep improving daily.

As you can in making literally open a front project, there are more than half are Node. Js relevant information, all kinds of package management, testing, ci, auxiliary module, if everybody to master these basic information is very good, so you learn a new framework, you are much faster than others, the most important thing is to learn the time, everywhere.

A lot of people ask me how do I become a Node.js giant? My answer is “keep writing articles and open source projects on cNode forum for 2 years, that’s enough. It’s easy to enter Ali Tencent. They will find you without you looking for them.”

From today on, I start to pay attention to open source projects and Node, and make progress every day

1.5. Part 4 Practice: From a recruitment perspective, what skills are required for Node.js development?

1.5.1. Recruitment criteria

Say first my hiring standards, when making technical director refers to the dispatching as long as you look good technical ability and attitude, to consider while doing the CTO team culture, character and can grow in the company, so different people interview depends on the point is not the same, I have face a lot of the Node. Js programmer, I’ve seen a lot of interview questions, summary, generally has the following 9 points:

  1. Basic Node.js features such as event-driven, non-blocking I/O, Stream, etc
  2. With respect to asynchronous process control, promises are mandatory
  3. Master at least one Web framework, such as Express, Koa, Thinkjs, Restfy, Hapi, etc., ask questions about problems and front-end optimizations
  4. Database related, especially SQL, cache, Mongodb, etc
  5. For common Node.js modules and tools, observe whether a person likes to learn and toss
  6. Plus points for familiarity with Linux and independent server deployment
  7. Js syntax and ES6, ES7, CoffeeScript, TypeScript, etc., to see if you care about new technologies, have + points
  8. Plus points for understanding the front end
  9. Have you ever participated in or written an open source project, technical blog, + points

Add: just look at the skills of the character of the people, do not recruit, white face Wolf

P6 Requirements (Voice)

Actively execute, assist the team to master a back-end language; Familiar with user experience knowledge; Understand software engineering. Proficient in browser working principle, familiar with HTTP protocol, familiar with design patterns. Ways to improve accessibility; Master data acquisition and analysis ability; Be familiar with maintainability issues. Develop, use, and promote productivity tools to improve productivity for yourself and your team. Refine reusable components and contribute high-quality code to the class library. Improve knowledge base actively; Share technical and professional knowledge across teams. Coach new skills growth; Assist supervisor in recruitment and team management.

1.5.2. Do people choose big companies or small companies?

I replied on Zhihu “What should I do when I receive an offer from a Fortune 500 company in the third month after job-hopping?”

1) Internet companies have priority, with large traffic, more talents, more opportunities and more standardized processes

2) Today’s Fortune 500 is not the same as before, pricewaterhousecoopers should be one of the four, do not know how information, you just need to compare with your current company.

3) Ask yourself what you want, money, experience, or time

If you’re young and comfortable, I suggest you switch. If you don’t want to move, learn everything you can before you move.

I am a pay cut to ali, for three reasons, one is something can be, the boss reuse you give you the opportunity, 2 it is within the group is open, it happened that I knowledge enough to see the benefits of them, is another kind of compensation, the third is the personal brand is an upgrade, the Wolf uncle career to this is enough, in can attack and defend, also is another kind of freedom!

Money is an advantage. Atmosphere, culture, faith

  • Cows are better than one
  • Business needs
  • You have more energy when you mature
  • Internal competition, survival of the fittest
  • With relative financial freedom, I was able to pursue my faith

A few days ago, I was chatting with @Suqian. I and @Deathmoon Skalete joined Ali one after another, and famous programmers in cNode community are also going to join Ali. At that time, everyone joked:

“The end of the front end is Ali, either in Ali or on the way to Ali.”

Another point to make is that PC and H5 sites are using Node.js as the API middle layer, and the best practices are well established and abundant. In the past, the front-end was still weak, and it would be nice to be able to cache + control page data and get a big performance boost. In 2018, try to use this as a keynote at QCON or ARCHSummit.

Busy and happy every day, that’s how I am now. In fact, I still want to do something. If you also want to work with me, please email your resume to [email protected], the team will recruit a large number of people, and you can also help recommend to other departments of the group.

The way big companies do things

  • Follow the rules. Don’t cross the line
  • Working hours are generally not too tight pressure, are negotiable, but the attitude must be good
  • Idle time oneself learn something, go to work want to learn relevant, come off work learn irrelevant. Don’t be silly.
  • Add some extra value and make your boss like you more
  • Be good at understanding and don’t let your boss say it twice.

A small company

  • Simple and rough, fast out things, the leader is most concerned about the progress
  • Strong executive force, meet Buddha kill Buddha, ghost kill ghost
  • Code quality is not something that many people care about, but you should pay attention to develop good habits
  • No opportunity to create their own opportunities. Build trust before you create opportunity.

Uncle Wolf often says: “Complain less, think more, the future will be better”. Most people like positive people, who are not afraid to avoid problems, and should believe that they can solve the problem, at most, the problem of time.

Another is: “Have no goals to look at money, have goals to look forward.” There are a lot of examples in history, when iOS development started around 2010, there were more people in the five figures who were dragging and dragging to build interfaces than there were in JAVA years. That’s how unfair the world is. But you can’t be too slow. That’s dangerous. Around 2016, the iOS development market was saturated. Many trained people could not find jobs, and companies were considering changing to React Native or WeeX or H5.

So, when you have the opportunity to move in a promising direction, you should study hard and be ready for the next stage. On the contrary, if you look for a place to retire, sooner or later you will encounter embarrassment. For example, many iOS programmers are now forced to learn React/Vue, which is not good, or even fired.

1.5.3. Youku – Advanced front-end development

The job description

  1. Support enterprise-level application background development, use front-end frameworks such as React to build background pages, and realize interaction requirements and back-end service connection;
  2. Design and develop general front-end components with modular ideas, and be able to optimize for OTT and mobile terminals;
  3. On the basis of understanding the front-end development process, combine the front-end reality to establish or optimize the tools to improve work efficiency;
  4. On the basis of understanding the product business, improve the user experience of the product, technology drives the development of the business;
  5. Focus on cutting-edge technology research, through new technology to serve the team and business;
  6. Develop product requirements using Weex technology.

Job requirements

  1. Proficient in the front-end technology, including the HTML/CSS/JavaScript/Node. JS, etc.;
  2. Master Bootstrap, jQuery, AngularJS, React and other frameworks, and have project practice;
  3. Familiar with front-end modularization, build and build tools such as Grunt, gulp, Webpack, etc.
  4. Familiar with at least one non-front-end language (such as Java/PHP/C/C++/Python/Ruby), project experience is a plus;
  5. Cross-terminal front-end development ability, proficient in at least one of the three directions of Web(PC+Mobile)/Node.js/Native App, preferably multiple, encourage exploration in the integration of Native and Web technologies;
  6. Strong learning ability, continuous enthusiasm for front-end technology, optimistic and cheerful personality, strong logic, good at cooperation with students in product, UED, back-end and other directions.

1.5.4. PixelLab

PixelLab is a research and development department jointly established with GM Lab of Taobao focusing on the direction of video algorithm, mainly involving spatial perception, track tracking, image segmentation, occlusion detection, photo-level rendering and other related technologies of video. It is used to realize the research and development of content implantation and post-production special effects in videos. It belongs to the scene of video MR, and is mainly applied to the research and development of advertising implantation platform. The direction is reliable and the boss is good. The positions mainly needed include image algorithm, 3D vision algorithm, rendering algorithm, WebGL and parallel computing, etc. Since algorithm recruitment is really difficult, I post the link of JD in the hope that there are suitable people for colleagues to promote.

1) Bachelor degree or above, more than 5 years working experience in development; 2) Solid foundation of computational geometry, familiar with common mathematical tools; 3) Familiar with WebGL, Canvas rendering development, Shader writing, familiar with Three. Js, OSG. Js is preferred; 4) Proficient in JavaScript language, HTML5, CSS3 and other technologies; 5) Familiar with the technical characteristics of mainstream mobile browser, mobile TERMINAL H5 project experience is preferred; 6) Mobile WebGL development experience is preferred; 7) Strong learning ability, strain capacity, excellent communication and coordination skills, strong execution ability, strong team spirit.

1.5.5. Ant Financial

Job Requirements:

  • Bachelor degree, more than 2 years development experience, familiar with common class libraries or frameworks, writing high quality front-end code;
  • Familiar with NodeJS, experience in NodeJS development, familiar with Express/ KOA framework, etc.
  • Familiar with React, Redux and related frameworks and technologies, experience in single page application development;
  • Proficient in ES6, GULP, Webpack and other specifications and technologies;
  • Good at Web performance optimization and front-end effect implementation;
  • Good team work spirit and active communication awareness, strong learning ability and new technology pursuit spirit, willing to share;
  • Large site development experience is preferred.

Our front end professional construction direction

  • Topic configurable componentization platform based on ReactJS
  • Nodejs-based UED services (browser-side Web page monitoring)
  • Nodejs cloud container platform based on Docker
  • Construction of front-end engineering system based on Webpack
  • React isomorphic framework based on EggJS
  • G2-based business data visualization component library
  • Large-scale image recognition/image processing /AR/VR/ voice interaction and other research fields to explore

1.5.6. Contact information

At present, Beijing, Hangzhou, Guangzhou, Shanghai, Shenzhen and Chengdu are all recruiting. If you also want to work with me, please email your resume to me at [email protected]. The team will recruit a large number of people, and you can also help recommend them to other departments of the group.

Have the opportunity to work with winter, Gou Stock, Yu Bo, Su Qian, Pu Ling, Dead horse, Right, Xu Fei, Ruan Yifeng, Tianzhu, Yu Bo and other gods.

Between you and me, THERE are other companies I can recommend.

1.6. The conclusion

Young dead knock, older point let younger brother dead knock, now catch an expert to have a meal together, nothing is a meal can not solve, not two meals

Engineers don’t code and stumble, they solve problems

  • Young dead knock is to develop skill, 30 years old can do this
  • After leading a team, we should know how to delegate tasks and let more people help you, not the more people we bring, the more tired we are
  • After the age of 30 is the stage of playing cards, skills accumulated enough to use, at this time to pay attention to social, play a combination of boxing to play better

Emphasize that I didn’t create turning 30. Most people assume that things like family, kids, house, car, money, management, power, desire, etc., are significantly more stressful after turning 30. What I feel most is that my body is not as good as before and my memory is obviously declining.

Uncle Wolf said, “Complain less, think more, the future will be better.”

Most people can not adhere to the fun, will not play, so complain more. Having fun is an ability, especially if it’s something as boring as writing code. The beginning may just want to earn some money, later become love, so beautiful. Just be happy every day.

In addition, time should also benefit processing, Wolf uncle always mentioned a word on the vegetable root tan: [idle to have a tight mind, busy to have the fun of leisure].

Everyone’s life has many obstacles, similar to the bottleneck, only suffering and persistence can break through, persistence will produce confidence, suffering will create opportunities. A person who is confident after suffering will have a better future.

If you have any questions, you can post at me in the CNode community, or ask questions on the Node stack public account.

1.7. Part 5 Q: Answer your questions

Answer a little too many questions, here will not be posted, if it is a new user and confused Node friends to listen to Live.

www.zhihu.com/lives/92868…