Path problems in read-write files
ReadFile () reads the./(relative path) parameter in the file function, relative to the path that executes the node command, rather than looking for the JS file that is being executed. To solve this problem:
__dirname (two underscore): Indicates the directory where the JS file is currently executing
__filename: Represents the full path of the currently executing JS file
let filename = __dirname+‘\\‘+‘hello.txt‘
In the code above: ' \ ' The first \ means the escape character, Hello.txt represents the file to be read
Path stitching through the path module
- Benefits of Path stitching using the path module: No consideration for operating system compatibility
let path = require(‘path‘); let filename = path.join(__dirname,‘hello.txt‘);
Create a folder from the FS module
For example, create an FS folder with the "Notes" folder under the FS folder
let fs = require(‘fs‘); fs.mkdir(‘./fs‘,function(err){ if(err){ throw err; } }); fs.mkdir(‘./fs/笔记‘,function(err){ if(err){ throw err; } });
Some problems to be aware of
- An asynchronous operation cannot catch an exception through Try-catch, and it needs to be judged by err to determine if there is an error.
- Synchronization operations can catch exceptions through Try-catch.
- Do not use
fs.exists(path,callback) to determine whether the file exists, directly determine the error.
- Path issues when working with files
- When reading and writing files './' means the path of the currently executing node command, not the path of the JS file being executed.
- __dirname is always "the directory of JS currently being executed"
- __filename represents "The file name of the JS being executed (including the path)"
Writing an HTTP service program through node. JS, a minimalist version
Steps
- Loading HTTP Modules
- Creating an HTTP Service
- To add a request event handler for an HTTP service object
Enable HTTP Service listener, ready to receive client requests
`
HTTP Service Program
1. Loading the HTTP service
Let HTTP = require (' http ');
2. Create an HTTP service object
Let server = Http.createserver ();
3. Listening for user request events
The Request object contains all the contents of the user request message, and the request object can get all the data submitted by the user.
The response object is used to correspond some data to the user and must use the response object when the server responds to the data to the client
Request shorthand for REQ response to Res
Server.on (' request ', function (req,res) {
Send back a response to the browser
Res.write (' Hello World ');
For each request server must end the response, otherwise the browser will assume that the server responds to a no end,
Res.end ();
})
4. Start the service
Server.listen (8080,function () {
Console.log (' server started, please visit ' http://localhost:8080 ');
})`
node. JS Learning 02