[] Basic concepts of node (reproduced)

Source: Internet
Author: User
Tags try catch
1. Compile helloword in nodejs to understand what nodejs is and what features nodejs has. 2. How to Use nodejs modules, how to load other modules (require), and how to call other modules (module, module. exports). What is the difference between a self-compiled module and a module under node_modules? What is the loading sequence? Write a node. js module by yourself. 3. What is NPM, NPM tool how to use NPM install NPM init NPM install XXX -- save-dev NPM remove XXX -- save -- Dev NPM update xxx package. meaning of items in the JSON file, understanding what they are. 2. What are the methods of the HTTP module? 2.1 use the HTTP module to simulate a GET request for a web page and image 2.2. In this request, add headers such as Cookie, content-type, timeout, and req to obtain the protocol type, host address, and port, status Code, set the character encoding, User-Agent, master the methods for adding various parameters to headers 2.3 simulate POST requests, submit to your own background, use the Content-Type formdata, application/X-WWW-form-urlencoded, and application/JSON to submit the request, formdata requires File Upload 2.4 to remember the important methods res in the HTTP module. on ('data', function (chunk) {}) req. on ('error', function (error) {}) req. methods such as End 2.5 get to know querystring, how to use the URL library, on the URL address bar Parse and master res. setheader text/explain, text/JSON text/html and other types of understanding 2.6 Use the Cheerio library to parse an image in a Web page, download images from the webpage. 3. Use the FS module in FS module 3.1 to read and write a text file. Learn how to use readfile, writefile, readfilesync, writefilesync, and append, understand the meaning of the parameters, such as the file mode = 0777. Remember to use the 3.2 buffer, read and write a file using the buffer, and refresh the buffer. Master the file stream, capture, interrupt, and stop the resume and pause of open, data, and close events of the file stream event listener; master the pipe pipeline stream read and write files; 3.3 FS create and delete directories, create multi-level directories, read the multi-level directory 3.4 FS to modify the directory permission, move the file/folder 3.5 to implement a copy file module, respectively Use readfilesync + writefilesync and readstream + writestream 4. Master the events module and understand what event listening is, how to create the event listener eventemitter, and add the event listener addlistener, trigger event listening emit 5. Master the path module 5.1 to obtain the absolute path. isabsolute 5.2 obtains the path of the folder. dirname 5.3 obtains the part after the path point, which is equivalent to obtaining the suffix path. extname 5.4 converts the string in the path to the object path. parse is like XXXX? Convert A = B & C = d to {A: B, C: d} 6. OS module 6.1 OS host name OS. hostname () 6.2 operating system name OS. the release version of the operating system OS. release () 6.4 total system memory OS. totalmem () 6.6 CPU information OS. CPUs () 6.7 get the NIC list OS. networkinterfaces () 7. The absolute path of the nodejs Global Object 7.1 _ filename script file is 7.2 setTimeout, cleartimeout, setinterval, clearinterval, and console. log, console. error, console. dir 7.3 rocess module 7.3.1 process. stdin process. stdout implements a command line window, which can be input in Chinese, English, and numbers. It is triggered by 7.3.2. Process. on ('exit ', function () {}) 7.3.3 process. env returns the current environment variables, such as develop, test, and production. If PM2 is used for management. set HTTP Module 9 and async module series (tasks, [callback]) in JSON Startup File (no data exchange between multiple functions) parallel (tasks, [callback]) (parallel execution of multiple functions) waterfall (tasks, [callback]) (sequential execution of multiple functions, and the previous output is the last input.) Auto (tasks, [callback]) (multiple functions are dependent, some are executed in parallel, and some are executed in sequence) whilst (test, FN, callback) (with the while that can be called asynchronously) until (test, FN, CA Llback) (similar to while, but with the opposite judgment condition) Queue (the number of worker queues can be set) iterator (tasks) (wrap several functions as iterator) apply (function, arguments ..) (Pre-bind parameters to the function) nexttick (callback) (consistent behavior between nodejs and the browser) 10. Q module (used by promise) 10.1. A common promise returns two functions, first successful. then (result). The call is triggered when the second fails. fail (error) is similar to the finally in try catch finally, which is used to recycle resources (shut down databases and services ). FIN () function 10.2, two chained operations, one is written in the callback mode inside the function return GetUserName (). then (function (username) {return getuser (Use Rname ). then (function (User) {// if we get here without an error, // The value returned here // or the exception thrown here // resolves the promise returned // by the first line}); one is external function, return GetUserName () in linear mode (). then (function (username) {return getuser (username );}). then (function (User) {// if we get here without an error, // The value returned here // or the exception thrown here // Resolves the promise returned // by the first line}); 10.3, Q. if all promises are successful, the then (result) function is executed. If one of them rejects reject, the system immediately exits and enters the fail (error) function 10.4, Q. allsettled, then after all the promises are executed, fulfilled (completion state), or rejected (rejection state) 10.5, Q. any: if any of the promises arrays is successfully executed, the then (result) function is executed. If all the items fail, the system enters fail (error) function 10.6 and the Spread Function allow promise to return multiple values 10.7 and function queue. This function is used for recursion. Given the initial value, it calls the normal version return funcs in a chain. reduce (function (SOFAR, f) {return sof AR. then (f) ;}, Q (initialval); compact version return funcs. reduce (Q. when, Q (initialval); 10.8. Progress reminder: the third function of the Progress notification then function, or promise. progress (function (Progress) {}) 10.9, end of execution end chain promises, use. done functions 10.10 and later 1-7 assume that you have created promise. If you want to create a blank promise, you need to call Q. fcall return Q. fcall (function () {return 10;}); 10.11. Use deferreds to create the promise object var deferred = Q. defer (); FS. readfile ("foo.txt", "UTF-8", functio N (error, text) {If (error) {deferred. reject (New error (error);} else {deferred. resolve (text) ;}}); Return deferred. promise; 10.12. Use Q. delay creates the promise object function delay (MS) {var deferred = Q. defer (); setTimeout (deferred. resolve, MS); Return deferred. promise;} 10.13. Use Q. timeout creates the promise object function timeout (promise, MS) {var deferred = Q. defer (); q. when (promise, deferred. RESOLVE); delay (MS ). th En (function () {deferred. reject (New error ("timed out") ;}); return deferred. promise;} Of course, deferred can be used. notify to execute, progress reminder progress notification function requestoktext (URL) {var request = new XMLHttpRequest (); var deferred = Q. defer (); Request. open ("get", URL, true); Request. onload = onload; request. onerror = onerror; request. onprogress = onprogress; request. send (); function onload () {If (request. st ATUS === 200) {deferred. resolve (request. responsetext);} else {deferred. reject (New error ("status code was" + request. status) ;}} function onerror () {deferred. reject (New error ("can't xhr" + JSON. stringify (URL);} function onprogress (event) {deferred. Y (event. loaded/event. total);} return deferred. promise;} can also use Q. promise to execute, progress reminder promise notification function requestoktext (URL) {re Turn Q. promise (function (resolve, reject, publish y) {var request = new XMLHttpRequest (); Request. open ("get", URL, true); Request. onload = onload; request. onerror = onerror; request. onprogress = onprogress; request. send (); function onload () {If (request. status = 200) {resolve (request. responsetext);} else {reject (New error ("status code was" + request. status) ;}} function onerror () {reject (ne W error ("can't xhr" + JSON. stringify (URL);} function onprogress (event) {Policy (event. loaded/event. total) ;}}}11. Express module 11.1. Master how to create an HTTP server using express modules. 11.2, request, and response object: the request object-request object indicates an HTTP request, including the request query string, parameters, content, HTTP header, and other attributes. Common attributes: req. APP: When callback is an external file, use req. the app accesses the express instance req. baseurl: Obtain the URL path req currently installed on the route. body/req. cookies: Obtain "request subject"/cookies req. fresh/req. stale: determines whether the request is "fresh" req. hostname/req. IP: Get host name and IP address req. originalurl: Get the original request URL req. params: Obtain the parameters req of the route. path: Obtain the Request Path req. protocol: Obtain the protocol type req. query: Obtain the URL query parameter string req. route: Obtain the current matched route req. subdomains: Obtain the subdomain req. accpets (): Check the request type req in the request's accept header. acceptscharsets/req. ACCE Ptsencodings/req. acceptslanguages req. get (): Get the specified HTTP Request Header req. is (): Determine the MIME type response object-response object of the request header content-type to indicate the HTTP response, that is, the HTTP response data sent to the client when the request is received. Common attributes include res. APP: Same as req. the app is the same as res. append (): append the specified HTTP header res. set () in res. after append (), the previously set header res will be reset. cookie (name, value [, option]): sets cookie opition: domain/expires/HTTPOnly/maxage/path/secure/signed res. clearcookie (): Clear cookie res. download (): transfers the file res in the specified path. get (): returns the specified HTTP header res. JSON (): Send the JSON response res. jsonp (): Send jsonp response res. location (): only sets the location HTTP header for the response, and does not set the status code or close response res. redirect (): Set the location HTTP header for the response and set the status code 302 res. send (): Send the HTTP Response res. sendfile (path [, options] [, FN]): transfers the file in the specified path. The Content-Type RES is automatically set based on the file extension. set (): sets the HTTP header. You can set multiple headers at a time when an object is imported. Res. status (): sets the HTTP status code res. type (): Set the MIME type 11.3 of Content-Type, Master express middleware Writing Method 11.4, Master express route Writing Method 11.5, and express. static middleware to set the static file path 11.6, express File Upload method, form enctype attribute is set to multipart/form-data, req. files 11.7, cookieparser to manage cookies



 



[] Basic concepts of node (reproduced)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.