Node.js is an environment in which you can run JavaScript in addition to a browser

Run JavaScript in Node.js

  • Script mode

Node path/filename.js (Enter)

  • Interactive mode Explore JavaScript objects using TAB auto-completion (e.g. Math. Then press TAB twice) to click the command (e.g., type.help and press Enter)

JS code (Enter) Run the code. Exit or press CTRL + C twice to exit interactive mode

Global object

The global object in Node.js is the global object in js on the browser side, and the global object is the Window

The global object under Node.js is global

  • In interactive mode, declared variables and functions belong to global. For example :var a = 1; Global. a can be accessed
  • In script mode, declared variables and functions are not global. For example :var a = 1; Global. a cannot be accessed

Global function

Global functions under Node.js

  • Global function provided by the JavaScript language, in the Node. Js is available under the parseInt/parseFloat/isNaN/isFinite/eval. One-time timer (setTimeout/clearTimeout) Periodic timer (setInterval/clearInterval)
  • The Node.js environment also provides some global functions to mediate/clearImmediate timers (setImmediate/clearImmediate)
var num = 3.14
console.log(parseInt(num))

var timer = setTimeout(() = > {
    console.log(1)},2000)

// Clear a one-time scheduled task
// clearTimeout(timer)

Execute immediately before the event queue starts
setImmediate(() = > {
    console.log(2)})// Execute immediately after the main process ends
process.nextTick(() = > {
    console.log(7)})Copy the code

Node. Js module

Core module – Console

  • Output content in the console, through different colors to identify different variable types
  • The console can output multiple variables at a time, separated by commas
  • Official documentation :nodejs.cn/api/console…
console.log("1")
console.log(1)

var obj = {
    name: 'Tom'.age: 18
}
console.log(obj)
console.table(obj)

// The timer function
console.time('for') // Start the timer
for (let i = 0; i < 1000000; i++) {

}
console.timeEnd('for') // The timer ends

console.time('while')
var i = 0
while (i < 1000000) {
    i++;
}
console.timeEnd('while')
Copy the code

Core module – Process

  • Process provides information about the current Node.js process
  • Process is a global variable and can be used without requiring
  • Official documentation :nodejs.cn/api/process…
// Process is a global variable
// const process = require('process')

// console.log(process)

// Output the node version
console.log(process.version)

// Output the operating system architecture
console.log(process.arch)

// Output the operating system platform
console.log(process.platform)

CWD = current working directory
console.log(process.cwd())

// Environment variables
console.log(process.env)
// Customize environment variables
process.env.NODE_ENV = 'develop'
console.log(process.env)

// Get the process number
console.log(process.pid)

// Kill process process.kill(process id)
Copy the code

Core module – PATH

  • The path module provides functions for path operations • current directory./ • upper directory.. /
  • Before it can be used, it needs to be introduced by require
  • Official documentation :nodejs.cn/api/path.ht…
// Introduce the path module
const path = require('path')

// Get the current file path
console.log(process.cwd())

// dir = directory Directory
console.log(__dirname) // Get the current file path

// D:\cliu\Desktop\node\03.core_module\path.js
console.log(__filename) // Get the full path to the current file

// Get the file extension ext = extension
console.log(path.extname(__filename))

// Get the directory part of the path
console.log(path.dirname(__filename))

// Get the file name in the path
console.log(path.basename(__filename))

const t = path.join(__dirname, '.. ')
console.log(t)
// Merge multiple paths
const a = path.join('D:/'.'a'.'b'.'c.png')
console.log(a)
//D:\a\b\c.png
Copy the code

Core module – FS

  • File System (FS) provides apis for file operations • File operations • Directory operations
  • Before it can be used, it needs to be introduced by require
  • Official document :nodejs.cn/api/fs.html

File write operation

// Write the file
const fs = require('fs')

// Clear the write
// fs.writeFile(' file path ', 'write content ', callback function)
fs.writeFile('./1.txt'.'Once there was a song, she touched me'.(err) = > {
    if (err) throw err
    console.log('Write succeeded')})Copy the code

File read operation

const fs = require('fs')
const path = require('path')

/ / read the file
// Specify the path to the destination file
// var filename = __dirname + '/1.txt'
var filename = path.join(__dirname, '1.txt')

// Syntax: fs.readfile (' file path ', callback function)
fs.readFile(filename, (err, data) = > {
    if (err) throw err
    // Data is binary data, which is displayed in hexadecimal format by default
    console.log(data.toString())
})
Copy the code

File deletion operation

const fs = require('fs')

// Syntax: fs.unlink(' file path ', callback function)
fs.unlink(__dirname+'/1.txt'.(err) = > {
    if (err) throw err
    console.log('Deleted successfully')})Copy the code

File appending operation

const fs = require('fs')

// Append to write
Fs.appendwrite (' file path ', 'write content ', callback function)
fs.appendFile(__dirname+'/2.txt'.'There was once a song, and she sang: \n'.(err) = > {
    if (err) throw err
    console.log('Append write succeeded')})Copy the code

Create a directory

const fs = require('fs')

// Create directory
// Syntax: fs.mkdir(' directory path ', callback function)
fs.mkdir('./d1'.(err) = > {
    if (err) throw err
    console.log('Created successfully')})Copy the code

Delete the directory

const fs = require('fs')

// Delete the directory
// Syntax: fs.rmdir(' directory path ', callback function)
fs.rmdir('./d1'.(err) = > {
    if (err) throw err
    console.log('Deleted successfully')})// declaration: rmdir can only delete empty directories
// 1. Delete the common files in the directory.
// 2. Use rmdir to delete an empty directory
Copy the code

Rename directory

const fs = require('fs')

// Rename the directory
// Syntax: fs.rename(old name, new name, callback function)
fs.rename(__dirname+'/d1', __dirname+'/d2'.(err) = > {
    if (err) throw err
    console.log('Rename successful')})Copy the code

Read the directory

const fs = require('fs')

/ / read directory
// Syntax: fs.readdir(' directory path ', callback function)
fs.readdir(__dirname, (err, data) = > {
    if (err) throw err
    // console.log(data)
    // Iterate over the path contents
    data.map((d) = > {
        // console.log(d)
        fs.stat(__dirname+"/"+d, (err, stat) = > {
            if (err) throw err
            if (stat.isDirectory()) {
                // Check whether the current file is a directory
                console.log('Directory:', d)
            } else if (stat.isFile()) {
                // Check whether the current file is a normal file
                console.log('File:', d)
            }
        })
    })
})
Copy the code

Synchronization function

const fs = require('fs')

// Check whether the file exists
// Then, if the file exists, delete it
if (fs.existsSync(__dirname+"/1.txt")) {
    fs.unlinkSync(__dirname+"/1.txt")}else {
    console.log('File does not exist')}Copy the code

Copy and compress files

const fs = require('fs')
const path = require('path')

// copy SRC /style. CSS to dist/
const dist = path.join(__dirname, 'dist')

fs.readFile('./src/style.css'.(err, data) = > {
    if (err) {
        throw err
    } else {
        console.log(data.toString())

        // Make sure the dist directory exists
        if(! fs.existsSync(dist)) { fs.mkdirSync(dist) }// Compress the file: remove unnecessary comments or Spaces
        // * The contents of the comment */
        var mydata = data.toString().replace(/\s+/g.' ').replace(/ / \ \ * {1, 2} [\ s \ s] *, *, / / g.' ')

        // Write the read content to the target file
        fs.writeFile(dist+'/style.min.css', mydata, (err) = > {
            if (err) throw err
            console.log('success')})}})Copy the code

File stream

const fs = require('fs')

// 1. Create a read stream
var readStream = fs.createReadStream('./file2.txt')

// 2. Create a write stream
var writeStream = fs.createWriteStream('./file_stream.txt')

// 3. Pipe the read stream to the write stream
readStream.pipe(writeStream)
Copy the code

Core module – HTTP

  • The HTTP module can publish Web services
  • Before use, introduce via require
  • Official documentation :nodejs.cn/api/http.ht…
const http = require('http')

1. Create a server
/** * req = request Request * res = Response Response */
const server = http.createServer((req, res) = > {
    res.statusCode = 200
    res.setHeader('Content-Type'.'text/plain; charset=utf-8')
    res.end('Hello: node.js')})// 2. Publish web services
const port = 3000
const host = 'localhost'
// Go to http://localhost:3000 in your browser and see the results
server.listen(port, host, () = > {
    console.log(The server runs in http://${host}:${port}`)})Copy the code

Custom modules

  • Each individual.js file in Node.js is a module

  • Each module has a module variable that represents the current module

  • Module exports only properties or methods that are exported (module.exports) can be called externally

  • Unexported content is module private and cannot be accessed externally • When used, it is imported via require

const PI = 3.14

// Calculate the circumference of a circle
function perimeter(r) {
    return 2 * PI * r
}

// Calculate the area of the circle
function area(r) {
    return PI * Math.pow(r, 2)}// Attributes or methods in a module must be exported before they can be used
module.exports = {
    perimeter,
    area
}
Copy the code
// Import the file module
const circle = require('./circle')

const r = 10

console.log('Circumference:', circle.perimeter(r))
console.log('Area:', circle.area(r))
Copy the code

Module loading logic

File module

  • The official module require(‘path’) introduces the official core module

  • Custom module require(‘./circle’) introduces its own module, the suffix.js can be omitted

The directory module

  • Require (‘./dir01’) starting with path find the dir01 directory in the specified path and import the entry file

  • Require (‘dir02’) look for dir02 in the node_modules directory of the current directory. If you can’t find it, go up to the top directory. Once you have found the directory module dir02, import the entry file in dir02.

  • Json file is specified by its main property. If it cannot be found, index.js is imported by default