This is the 21st day of my participation in Gwen Challenge

FS module

File system File system

This module is currently used to manipulate files and folders

Create a file

fs.appendFile(filePath, content, callback); FilePath: indicates the filePathcontent: File contentcallbackThis method can be used in two ways: first, to create a file (when the file does not exist), and second, to append (when the file already exists)Copy the code
// Import the FS module
var fs = require("fs");

// Create a file
fs.appendFile("./a.txt"."This is a TXT file".function(err) {
	// The current function is the callback function after the creation of the file
	// Err indicates exceptions that may occur during creation
	console.log(err);
	console.log("Created");
});

console.log(1);
Copy the code

Output:

Read the file

fs.readFile(filePath, callback); FilePath: indicates the filePathcallback: callback functionerr: Errors that may occur during the read process Err Yes when no errors are encounterednullError object when an error occursdata: Read the contents of the file to its type when bufferCopy the code

Demo:

fs.readFile("index.html".function(err, data) {
	console.log(err);
	console.log(data);
	console.log(data.toString());
})
Copy the code

Output:

Delete the file

fs.unlink(filePath, callback); FilePath: indicates the address of the deleted filecallback: callback functionCopy the code

Demo:

/ / introduction of the fs
var fs = require("fs");

// Call the unlink method to delete the file
fs.unlink("./index.html".function() {
	console.log("Delete")})Copy the code

rename

fs.rename(oldPath, newPath, callback); OldPath: the original pathnewPathA new approach:callback: callback functionCopy the code

Demo:

var fs = require("fs");
fs.rename("a.js"."b.js".function(err) {
	console.log("Rename")})Copy the code

Creating a folder

fs.mkdir(dirPath, callback); DirPath: indicates the folder pathcallback: callback functionCopy the code

Demo:

var fs = require("fs");
fs.mkdir("a".function() {})Copy the code

Delete folders

fs.rmdir(dirPath, callback); DirPath: indicates the folder to be deletedcallbackNote: This method can only delete empty directoriesCopy the code

Demo:

var fs = require("fs");

fs.rmdir("abc".function(err) {
	console.log(err);
})
Copy the code

If you delete a non-empty directory:

Read folder

fs.readdir(dirPath, callback); DirPath: indicates the folder to be readcallback: callback functionerr: Error objectarr: An array of all files and folder names in the read folderCopy the code

The Demo:

var fs = require("fs");

fs.readdir("./ New folder".function(err, arr) {
	console.log(err);
	console.log(arr);
});
Copy the code

Determine if a target is a file or folder

fs.stat(path, callback); Path: indicates the destination pathcallback: callback functionerr: Error objectstate: generates an object based on the target that has a method isDirectory() that returns a Boolean value if it istrueIndicates a folder otherwise indicates a fileCopy the code

Demo:

var fs = require("fs");

fs.stat("./ create new folder /aaa.txt".function(err, state) {
	console.log("aaa.txt" + (state.isDirectory() ? "Yes" : "Not") + "A folder");
})

fs.stat("./ New folder /aaaa".function(err, state) {
	console.log("aaaa" + (state.isDirectory() ? "Yes" : "Not") +"A folder");
})
Copy the code

Results:

Delete a non-empty directory

var fs = require("fs");

function del(dirPath) {
	// Read the folder
	var arr = fs.readdirSync(dirPath)
	/ / loop
	for(var i = 0; i < arr.length; i++) {		var state = fs.statSync(dirPath + "/" + arr[i]);
		// console.log(dirPath + "/" + arr[i] + (state.isDirectory() ? "Yes ":" no ") +" a folder ");
		if (state.isDirectory()) {
			del(dirPath + "/" + arr[i]);
		} else {
			fs.unlinkSync(dirPath + "/" + arr[i])
		}
	}
	// Finally delete the folder
	fs.rmdirSync(dirPath);
}

module.exports = del;
Copy the code

URL module

This module is used to process URL strings and URL objects

URL.parse

The parse method is used to parse a URL string into a URL object

Demo:

There are the following strings:var str = http://www.icketang.com/pc/index.html?username=laosi&password=123#cccTo retrieve a portion of a URL: Import the URL modulevar url = require("url"); Call the parse method to parse the string url.parse(STR); The return value is an objectCopy the code

The objects are as follows:

Static server

// Introduce the HTTP module
var http = require("http");
// Import the fs module
var fs = require("fs");
// Introduce the URL module
var url = require("url");

/ / MIMEType daqo
var MIMEType = {  
	"*"	      :"application/octet-stream"."323"	    :"text/h323"."acx"	    :"application/internet-property-stream"."ai"	    :"application/postscript"And... }// Create a server
var server = http.createServer(function(req, res) {
	// if (req.url === "/index.html") {
	// fs.readFile("./index.html", function(err, data) {
	// res.end(data);
	/ /})
	// return;
	// }

	// if (req.url === "/second.html") {
	// fs.readFile("./second.html", function(err, data) {
	// res.end(data);
	/ /})
	// return;
	// }
	// We find that when we call /index.html, we're reading./index.html when we call /second.html, we're reading./second.html. After reading the
	// console.log(req.url);
	// Define a variable that accepts a formatted object
	var url_obj = url.parse(req.url);
	// console.log(url_obj);
	var pathName = url_obj.pathname;
	fs.readFile("." + pathName, function(err, data) {
		if (err) {
			res.setHeader("content-type"."text/plain; charset=utf-8");
			res.end("Sorry, you read." + pathName + "Doesn't exist.");
			return;
		}
		// Get the extension name index.html
		var extName =  pathName.slice(pathName.indexOf(".") + 1);
		res.setHeader("content-type", MIMEType[extName] + "; charset=utf-8") res.end(data); })})// Listen on the port number
server.listen(3000);
Copy the code

HTTP Request Mode

A GET request

HTTP requests can be divided into different types based on purpose. Multiple address bar input request sent by IMG tag Link tag request sent by script tag Request sent by form Ajax The data carried by the request body is called Query for easy sharingCopy the code

A POST request

Post requests represent "placing content on the server" features: Less triggering methods Forms High security of Ajax because the data carried during the request is placed in the request body and not easy to shareCopy the code

NodeJS handles GET requests

Requests sent from the front end:

http://localhost:3000/login? username=%E7%8E%8B%E8%80%81%E4%BA%94&psd=123
Copy the code

Back-end processing:

The so-called back-end processing is actually the data sent from the front end or save, or query and other processing methods.

var url_obj = url.parse(req.url, true); 
// Define the interface to handle /login
if (pathName === "/login" && req.method.toLowerCase() === "get") {
	console.log(url_obj.query.username);
	console.log(url_obj.query.psd);
	res.end("hello");
	return;
}
Copy the code

When the second argument to url.parse is true, the parsed Query is also converted to an object.

When to false:

Is true: