Finals week-Learn a little bit about node.js while I’m at it

Table of contents

A preliminary understanding of Node

effect

Notice

Node.js file system

node import file system module

Read the contents of a file

Example: 

the difference:

Write content to file

Example:

 fs module-path dynamic splicing problem

Path module in Node.js

 Import path path module

Path splicing

 Example:

Get the file name of the file path

Example 

Get file extension in path

Example


A preliminary understanding of Node

Simply put, Node.js is JavaScript running on the server.

effect

① Based on the Express framework ( http://www.expressjs.com.cn/ ), Web applications can be quickly built
② Based on the Electron framework ( https://electronjs.org/ ), cross-platform desktop applications can be built
③ Based on the restify framework ( http://restify.com/ ), API interface projects can be quickly built
④ Read, write and operate databases, create practical command line tools to assist front-end development, etc...

Notice

① The browser is the front-end running environment for JavaScript.
② Node.js is the back-end running environment for JavaScript.
③ DOM and BOM cannot be called in Node.js
Browser built-in API.

Node.js file system

node import file system module

var fs=requier("fs");

Read the contents of a file

1. Asynchronous reading

fs.readFile(path[,options],callback);
1.path is a required parameter, indicating the path of the file
2.option is an optional parameter, indicating the encoding format to read the file
3.callback is required Parameter, indicating that after the file is read, the read result is obtained through the callback function

2. Synchronous reading

readFileSync(path[, options]) reads files synchronously

path: file path
options: optional parameters used to configure options for reading files

Example: 

//导入fs模块
var fs = require('fs');

//异步读取
fs.readFile('文件路径', (err, data) => {
    if (err) {
        console.log('读取失败');
        return;
    }
    console.log(data.toString());
})
console.log("111111");
//会先打印出111111,之后,如果读取成功,会打印出data.toString,如果失败,会打印出读取失败

//同步读取
let data = fs.readFileSync('文件路径');

console.log(data.toString());

the difference:

Synchronous : The previous code is executed first, and the following code needs to wait for the execution of the previous code to be executed. Asynchronous
: The code is executed in no particular order, which means that the execution of the previous code will not cause the subsequent code to block, so the execution results of the asynchronous code are in the order Not necessarily

It is recommended to use asynchronous methods. Compared with synchronization, asynchronous methods have higher performance, faster speed, and no blocking.

For asynchronous, the code runs from top to bottom. After reaching the place, it runs the io disk thread, which is more efficient.

Write content to file

Write content asynchronously
fs.writeFile(file, data[, options], callback);
  • file  - file name or file descriptor.

  • data  - the data to be written to the file, which can be a String or Buffer object.

  • options  - This parameter is an object containing {encoding, mode, flag}. The default encoding is utf8, the mode is 0666, and the flag is 'w'

  • callback  - callback function. The callback function only contains error information parameters (err) and is returned when writing fails.

Write content synchronously

  fs.writeFileSync(file, data[, options], callback);

   file The path to the file to write to
        data content to be written
        options configuration object (optional)
            encoding encoding default utf8
            flag operation type default w
            The permissions of the mode file are 666 by default and generally do not need to be passed.

Streaming content

 Other file writing methods write one content into the file at a time.
 If the file is too large, it will cause the running speed to be too slow and seriously affect the performance of the program.
 Streaming file writing is suitable for larger files. Write, you can output multiple contents to the file multiple times
and write appended

fs.appendFile('File path','\r\nYou can become a teacher by reviewing the past and learning the new')

Among them "\r\n" is the function of line break

Example:

//导入fs模块
const fs = require('fs');

//写入文件
fs.writeFile('../../wenzi/座右铭.txt', '三人行,则必有我师焉', err => {
    //写入失败:错误对象,写入成功null
    if (err) {
        console.log('写入失败');
        return;
    }
    console.log('写入成功');

})

console.log(1 + 1);

//同步写入
// fs.writeFileSync('../../wenzi/座右铭.txt', '三人行,则必有我师焉);
//1.导入Fs
const fs = requier('fs');

//2.创建写入流对象
const ws = fs.createWriteStream('文件路径');

//3.write
ws.write('11111111\r\n');
ws.write('2222222\r\n');
ws.write('3333333333\r\n');
ws.write('4444444444\r\n');

//4.关闭通道
ws.close();



 fs module-path dynamic splicing problem

When using the fs module to operate files, if the provided operation path is a relative path starting with ./ or ../ , it is easy to cause dynamic path splicing errors.
Reason: When the code is running, the full path of the operated file will be dynamically spliced ​​from the directory where the node command is executed .
Solution: When using the fs module to operate files, provide the complete path directly instead of providing a relative path starting with ./ or ../ to prevent dynamic path splicing problems.

Path module in Node.js

The path module is a module officially provided by Node.js for processing paths . It provides a series of methods and attributes to meet users' needs for path processing.

 Import path path module

const path=require('path');

Path splicing

Note: In the future, all operations involving path splicing must be processed using the path.join() method . Do not use + directly to concatenate strings.

path.join([...paths]);

  ...paths <string> Sequence of path fragments
  Return value: <string>

 Example:

const pathStr=path.join('/a','/b/c','../','./d','e');
console.log(pathStr);//输出\a\b\d\e

const pathStr2=path.join(_dirname,'./files/1.txt');
console.log(pathStr2);//输出 当前文件所处的目录\files\1.txt

Get the file name of the file path

Using the path.basename() method, you can get the name part of a file from a file path:

path.basename(path[,ext]);

parameter

path <string> required parameter, a string representing a path

 ext <string> optional parameter, indicating the file extension
returned:

 <string> represents the last part of the path

Example 

const fpath='/a/b/c/index.html';//文件存放的路径

var fullName=path.basename(fpath);
console.log(fullName); //输出index.html

var nameWithoutExt=path.basename(fpath,'html');
console.log(nameWithoutExt);//输出 index

Get file extension in path

Use the path.extname() method to get the extension part of the path
path.extname(path);
parameter
path <string>Required parameter, a string representing a path
return:
<string> Returns the obtained extension string

Example

const fpath='a/b/c/index.html';//路径字符串

const fext=path.extname(fpath);
console.log(fext);//输出 .html

Guess you like

Origin blog.csdn.net/www340300/article/details/131270946