Node learning notes read and write files and opening the first web server operation example

This example describes the Node read and write file and the first web server operation. Share to everyone for your reference, specific:

JS in Node has the ability of the file operation

Load it with a request method FS core module

* Require is a method
* His role is to load the module

* In Node, the module has three:
* Total core module Such as FS, HTTP
* The file module
* of the user yourself must be added ./
* In Node, there is no core scope, only the module scope
* External access is not To the internal
*, there is no external access

fs is the shorthand of Files-YSTEM, that is, the meaning of the file system

The first parameter is to read The second parameter is a return function, two parameters
error

If the read fails, Error is the error object
If reading is successful, Error is NULL
Data
If the reading failed, Data is undefined
If read success, error is the error object
success
data null
error error object


ERROR error object
   VAR FS = Require ('fs') 
  fs.rEadfile ('./ Test.txt', Function (ERROR, DATA) {//  // stored in the file is actually binary data 0 1 // If Error can determine if there is an error occurrence IF (Error) {Console.log (Error) Console.log ("File Read Failed") Return} console.log (data.tostring ())})  

Written file

First parameter: file path
second parameter: file content
third parameter: callback function
error

Success:
file write success
error is null
failed:
file write failed
Error is the error object

  VAR fs = Require ('fs'); // First parameter: File path // second parameter: file content // third parameter: callback function // error // Success: // File Write success // error is null // failed: // File write failed // error is the error object fs.writefile ('./ Hello.txt', "Give everyone a New Year ', Function (Error) {IF Error) {Console.log ("file write failed"); return} console.log ('file write success');})  

created Web server

Node specializes in a core module: http

HTTP

of this module is to create a written server

  VAR http = require ('http');  
What is the server going?

Provisioning Service
    Accept request
  • processing request
  • gives feedback (transmission response)
  • Registered Request Request Event
  • After the server receives the request, the Request request event triggered by the server is received, and then the second parameter callback process function
Server.on (‘Request’, Function () {console.log (‘Received a request’)}; // 4. Bind port number, start the server server. Listen (8080, function () {console.log (‘server startup, can be accessed by http://127.0.0.1:8080/)

I hope this article will help you NodeJS programming.
                     
© Copyright Notice
THE END
Just support it if you like
like0
share
comment Grab the couch

Please log in to comment