Node.js learning -01 Basic use
Execute JS scripts using Node
node Hello.js
Copy the code
const foo = 'Hello Node';
console.log(foo);
Copy the code
Note:
-
Do not name the file as Node.js
-
No window or document in Node (no DOM or BOM)
Node reads files
// 1. Load the fs core module using the require method
var fs = require('fs');
// 2. Read files
// The first argument is the path to the file to read
The second argument is a callback function
// Success: data data error: null
// Failed: data null error: error object
fs.readFile('./file.txt'.function(error, data) {
console.log(error);
// <Buffer 74 68 69 73 20 69 73 20 61 20 66 69 6c 65>
// Binary data is converted to hexadecimal
console.log(data);
console.log(data.toString()); // this is a file
// Simple error handling
if (error) {
console.log('File reading failed');
} else {
console.log(data.toString()); }})Copy the code
The Node to write files
var fs = require('fs');
fs.writeFile('./write.txt'.'Big brother and sister-in-law Happy New Year'.function(error) {
if (error) {
console.log('File write failed');
} else {
console.log('File write succeeded'); }});Copy the code
Simple HTTP service
The simplest HTTP service
// Build a Web server using Node
// 1. Load the HTTP core module
var http = require('http');
// 2. Create a Web server using the http.createserver () method and return a server instance
var server = http.createServer();
// 3. Receive the request, process the request, and send the response
// Register the request event
// When the client request comes in, the server automatically triggers the request event, and then executes the second argument: the callback handler
server.on('request'.function() {
console.log('Received client request');
});
// 4. Bind the port number to the server
server.listen(3000.function() {
console.log('The server started successfully and can be accessed at http://127.0.0.1:3000/');
});
Copy the code
Send a response
// Build a Web server using Node
// 1. Load the HTTP core module
var http = require('http');
// 2. Create a Web server using the http.createserver () method and return a server instance
var server = http.createServer();
// 3. Receive the request, process the request, and send the response
// Register the request event
// When the client request comes in, the server automatically triggers the request event, and then executes the second argument: the callback handler
// The callback function takes two arguments
// Request: request object, which can be used to obtain some request information from the client, such as the request path
// Response: a response object that can be used to send a response message to the client
server.on('request'.function(request, response) {
console.log('Received the request from the client. The request path is:' + request.url);
// Response has a write method that can be used to send response data to the client
// Write can be used multiple times, but the end must be used, otherwise the client will wait
// response.write('hello');
// response.write(' nodejs');
// Tell the client that the response is complete
// response.end('Hello World');
// Send different response results according to different request paths
Obtain the request path. 2. Determine the path and process the response
var url = request.url;
if (url === '/') {
response.end('index page');
} else if (url === '/login') {
response.end('login page');
} else {
response.end('404 Not Found');
}
// The response can only be strings, numbers, objects, arrays, or booleans
// var obj = {
// name: 'xx',
// age: 18
// };
// response.end(JSON.stringify(obj));
});
// 4. Bind the port number to the server
server.listen(3000.function() {
console.log('The server started successfully and can be accessed at http://127.0.0.1:3000/');
});
Copy the code
The core JS module in Node
Common core modules
- Fs file system
- HTTP Network Request
- OS Operating system
- The path path
- .
Module system in Node
moduleA.js
// require is a method used to load modules
// In Node, there are three types of modules
// 1. Named core module: fs, HTTP
// 2. User-written file module: js file commonjs
// 3. Third-party modules
console.log('a start');
require('./moduleB.js');
console.log('a end');
/** * a start * B module file is loaded to execute * a end */
Copy the code
moduleB.js
Console. log('B module file was loaded and executed ');Copy the code
- In Node, there is no global scope, only module scope, and objects with the same name in moduleA and moduleB do not conflict
- The outside does not affect the inside, and the inside does not affect the outside
Since modules are closed by default, how do you get module to module?
moduleB.js
var foo = 'bbb';
// Bind all members that need external access to exports
exports.foo = 'hello'; // The exported object
Copy the code
moduleA.js
var bExports = require('./moduleB.js');
console.log(bExports.foo); // 'hello'
Copy the code
IP address and port
IP identifies computers on the Internet, and ports identify applications on computers
The response Content type is content-type
- Default data sent by the server, UTF8 encoding
- However, without knowing the encoding of the browser’s response, the browser will parse according to the default encoding of the current operating system
- The default Chinese operating system is GBK
- Workaround: Tell the browser the correct encoding for what to send
response.setHeader('Content-Type'.'text/plain; charset=utf-8'); // Resolve Chinese garbled characters
Copy the code
Content-type: tells what type of data to send
- Text /plain Plain text
- text/html html
- text/css css
- imgae/jpep jpeg
Send the data in the file and the content-type Content type
var http = require('http');
var fs = require('fs');
var server = http.createServer();
server.on('request'.function(req, res) {
var url = req.url;
if (url === '/') {
fs.readFile('./resource/index.html'.function(err, data) {
if (err) {
res.setHeader('Content-type'.'text/plain; charset=utf-8');
res.end('File read failed, please try again later! ');
} else {
res.setHeader('Content-type'.'text/html; charset=utf-8'); res.end(data); }})}else if (url === '/ab2') {
fs.readFile('./resource/ab2.png'.function(err, data) {
if (err) {
res.setHeader('Content-type'.'text/plain; charset=utf-8');
res.end('File read failed, please try again later! ');
} else {
res.setHeader('Content-type'.'imgae/jpep; ');
res.end(data);
}
})
}
})
server.listen(3000.function() {
console.log('The server started successfully and can be accessed at http://127.0.0.1:3000/');
})
Copy the code