Nodejs Getting Started

Source: Internet
Author: User
Tags comparison table readfile

node. JS is not a language or a library or a framework, but a JS runtime environment , in simple terms, node can parse and execute JS codepreviously only the browser's JS engine can parse the execution of JS code, and then Google browser V8 JS engine was ported out of the development of Node this independent JS runtime environment, now rely on it, JS can be completely out of the browser to runbut JS in Node is somewhat different, there is no BOM, DOM, but also for JS to provide a lot of server-level API, such as file read and write, Network Service construction, network communication, etc. download version of the official website has two, LTS (long time support) long-term supported version, that is, stable version, current experience version, with the latest featuresDownload post-installation command-line input node--version or node-v To confirm the installation is successful then create a random JS file, such as the new folder named Nodedemo in the F-disk, create a new helloworld.js inside, the file name does not use node. js, preferably do not use Chinese
var str = "Hello world~"; Console.log (str);

In the directory where the JS file is opened DOS window, the node file name of the command to parse the execution of the corresponding file, at this time The Helloworld.js file is detached from the browser and executed by Node

file read/write

The browser's JS is not able to operate on the disk file, but the JS in Node has the ability of file operation

In Nodedemo new readfile.js and Book.txt,book plain text content only "ABC"

Readfile.js

 var  fs = require (' FS '); //  load FS Core module using require method  fs.readfile ('./book.txt ', function  (error,data) {//  The point represents the current directory, and the dot is the parent directory  if   (error) Console.log (    span> ' file read failed '  else   Console.log (data);});  /*  readfile () parameter has two, the file path and callback function callback function has two parameters, error and data read successfully: Data is the database, error null read failed: Data is Undefined, Error object  */  

FS is a shorthand for the file system, and the filesystem means that the core module of FS must be introduced to file operations in Node . in this core module, all the APIs related to file operations are provided, such as Fs.readfile, which is used to read files

Post-execution output

The ASCII decimal for ABC corresponds to 65 66 67, and the files are stored in binary, and the corresponding hexadecimal is output. Call the ToString method to output ABC

Console.log (Data.tostring ());

File writes are equally simple

// WriteFile () has three parameters: file path, file contents, callback function // error When writing succeeded is null, wrong object on Failure var fs = require (' FS '); Fs.writefile ('./song.txt ', ' street lamp dinner ',function  (error) {     if(Error)        console.log (' file write Failed ');     Else         console.log (' file write succeeded ');});

If the file you are writing to already has content, it will be overwritten

If the file does not exist beforehand, it will be created automatically, but if the folder where the file is located does not exist, the write fails

a simple HTTP service

Using Node makes it easy to build a Web server that is created under the Nodedemo directory Http.js

Http.js

//using node makes it easy to build a Web server that specifically provides a core module in node HTTPvarHTTP = require (' http ');//loading HTTP core modulesvarServer = Http.createserver ();//Create a Web server/*registers a request event, which triggers this event when the client requests the callback function has two parameter requests and response, which represent the request object and the Response object*/Server.on (' Request ',function(request,response) {Console.log (' received a request from ' + Request.url + '); Response.Write (' Hi~ ');    Response.End (); //the Write () method of the response object can be used more than once but must end with end () or the browser waits    //alsoeasy to use: Response.End (' hi~ '); The response can only be in binary buffer or string});//bind port number, start serverServer.listen (5000,function() {Console.log (' Server started successfully ');});

Port number range from 0 to 65535,QQ for 4000,tomcat server to 8080 ... Select a non-occupied port number

After the execution of the server successfully opened, this time the program occupies a DOS window, waiting for the client's request. Closing the window or CTRL + C will stop the server

IP can know which computer, through the port number to know which program in the computer, and IP 127.0.0.1 for native, so enter http://127.0.0.1:5000 in the browser address bar to access the server you just created

Port number 80 is the default access port for the Web server, and if you do not write the port number http://127.0.0.1, the browser will default to add http://127.0.0.0:80

The server receives the request and responds. Request.url Gets the portion of the path that follows the port number,/ represents the root directory. If requested http://baidu.com

Even if the end is not added/, the browser will also default to add

/favicon.icon is the icon that the browser will request by default

In this program, either the request/A or the/a/b will trigger the request event to respond to the same content

Core modules

Node provides many server-level APIs for JS, most of which are packaged in a named Core module

such as file operations. FS Core Module , HTTP module ,path path operation module ,OS OS information module , etc.

which module to use must be loaded with the require () method

Node supports modular programming with modules divided into named core modules (node-encapsulated modules) and custom Modules (user-written JS files)

Executive A.js

There is no global scope in Node only module scope , the scope of the module is simply a file scope, which is inaccessible beyond this file.

If in the browser, B.js str will overwrite the previous STR, so the output should be substring, but here because of the module scope, even if a.js loaded b.js, can not use the variables or functions in B.js

How do I make communication between modules? A exports object is provided in each file module, and the require () method returns the object, exports default is an empty object, which is {} , you can mount the members externally to be accessed in this object, that is , by using point syntax, to add properties or methods to the exports object

Chinese garbled

Server response Content If there is Chinese, the browser will appear garbled, this is because the server UTF-8 encoded response data, and the Chinese browser by default to GBK encoding to parse

The workaround is to set the response header information

var http = require (' http '); var server = http.createserver (); Server.on (' request ',function  (request,response) {    response.setheader (' content-type ', ' text/plain;charset=utf-8'// To put before write ()    Response.Write (' hi~ hello ');    Response.End ();}); Server.listen (' n ',function  () {    console.log (' Web Server running ');});

Different resources correspond to different Content-type , ordinary text is text/plain,html is text/html, more types can be viewed on-line comparison table

Typically only character data is specified for encoding, and images do not need to be encoded

Response.setheader (' Content-type ', ' image/jpeg ');

Nodejs Getting Started

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.