NodeJs built in module

@


System module fs -- file operation

f(file)s(system): file operating system

fs file system | node JS API document (nodejs.cn)

require('fs')

Want to use node The fs system module in the JS system module first needs to introduce fs into the current module.

const fs = require('fs');

fs.readFile()

fs.readFile(path[, options], callback);
Function: read the contents of the specified file

Format:

fs.reaFile('File path/File name'[,'Document code'], callback);
fs.readFile(path[, options], callback)

Parameter Description:

  • Path: required; string; indicates the file path
  • options: optional, indicating the encoding format to read the file
  • Callback: required. After reading the file, get the reading result through the callback function callback

give an example:

//readFile.js
//Example: in utf-8 encoding format, read the base. In the css directory of the upper level css and get the returned results
const fs = require('fs');
fs.readFile('../css/base.css', 'utf-8', (err, dataStr) => {
		if(err == null){
			console.log("File read succeeded, The content is: " + dataStr);
			//If the file is read successfully, the result of reading the file is returned
			return dataStr;
		}else {
			//Failed to read the file and output the error object, (err.message - > error brief information)
			console.log(err);
		}
	}		
)

Description of parameters (err, doc) in callback
err:

  1. If the file reading fails, the parameter err value: an object containing error information
  2. If the file is read successfully, the parameter err value is null

dataStr: is the result of file reading


It can be seen that callback in the node api is a callback function with error first

Operation results:

  • Read successful
  • read failure

Read the file through promise

const fs = require('fs');


function p1() {
    return new Promise((resolve, reject) => {
        fs.readFile('./1.txt', 'utf8', (err, result) => {
            resolve(result)
        })
    });
}

function p2() {
    return new Promise((resolve, reject) => {
        fs.readFile('./2.txt', 'utf8', (err, result) => {
            resolve(result)
        })
    });
}

function p3() {
    return new Promise((resolve, reject) => {
        fs.readFile('./3.txt', 'utf8', (err, result) => {
            resolve(result)
        })
    });
}

//Chain skill
p1().then((r1) => {
        console.log(r1);
        return p2();
    })
    //The reference object is the total parameter of the previous then method and the return value of the anonymous function
    .then((r2) => {
        console.log(r2);
        return p3();
    })
    .then((r3) => {
        console.log(r3)
    })


p1().catch((e1) => {
        console.log(e1);
        return p2();
    })
    //The reference object is the return value of the anonymous function of the total parameter of the previous catch method
    .catch((e2) => {
        console.log(e2);
        return p3();
    })
    .catch((e3) => {
        console.log(e3)
    })

fs.writeFile()

fs.writeFile(file, data[, options], callback)

Function: write content to the specified file

Format:

fs.writeFile(file, data[, options], callback)

Parameter Description:

  • File: required, string of file path, indicating the storage path of the file
  • data: required, indicating the content to be written
  • options: optional, indicating the format in which to write the file content. The default value is utf-8
  • Callback: required, the callback function after the file is written

give an example:

//writeFile.js
//Example: index. In the current directory Write content in HTML file
const fs = require('fs');
const content = '<h3>In use fs.writeFile Write file contents</h3>';
fs.writeFile('./index.html', content, err => { 
//If the file in this directory does not exist, the system will automatically create the file
	if(err != null){
		//File content writing failed
		console.log(err);
		console.log("-------------");
		console.log(err.message)
		return;
	}
	console.log('File written successfully');
	fs.readFile('../index.html', 'utf-8', (err, dataStr) => {
        console.log(dataStr);
    })
})

Parameter err description of callback:

  1. If the file is written successfully, the err value is null
  2. If file writing fails, err value: an object containing error information

Operation results:

be careful:

  1. fs. The writefile() method can only be used to create a file (when the specified file does not exist), not a path
  2. Repeated call to FS Writefile() writes to the same file, and the newly written content will overwrite the previous old content

fs module path dynamic splicing

When using fs module to operate files, if the operation path provided is in/ Or/ When the relative path at the beginning is, it is easy to have the problem of path dynamic splicing error.

Reason: when the code is running, it will dynamically splice the complete path of the operated file according to the directory where the node command is executed.

Solution: when using fs module to operate files, directly provide the complete path instead of providing it/ Or/ The relative path at the beginning, so as to prevent the problem of path dynamic splicing.

//Do not use/ Or/ Such relative path
fs.readFile('./files/1.txt', 'uft-8', function(err, dataStr){
})

// Use full path
fs.readFile(__dirname + '/files/1.txt', 'uft-8', function(err, dataStr){
})


System module path -- path operation

global.__dirname

__dirname

Function: returns the absolute path of the current module


Relative path VS absolute path

  • In most cases, absolute paths are used because relative paths are sometimes relative to the current working directory of the command-line tool
  • The absolute path will be selected when reading the file or setting the file path
  • Use__ dirname gets the absolute path where the current file is located
  • The relative path can be written in the require() method, which is relative to the directory of the current module, rather than the current working directory of the command-line tool
/*
test.js
*/
var first = 'hello nodejs';
console.log(first);
/*
relativeOrAbsolute.js
*/
const fs = require('fs');

fs.readFile('./test.js', 'utf8', (err, doc) => {
    console.log(err)
    console.log(doc)
});

The current command line window tool working directory and file relativeorabsolute JS directory mismatch, node JS running result:

Use__ dirname returns the absolute path of the read file to improve the code

/*
relativeOrAbsolute.js
*/
const fs = require('fs');
const path = require('path');

console.log(__dirname);//Get the absolute path of the current module
console.log(path.join(__dirname, 'test.js'))//Get the absolute path of the target file

fs.readFile(path.join(__dirname, 'test.js'), 'utf8', (err, doc) => {
    console.log(err)
    console.log(doc)
});



require('path')

Want to use node The path system module in the JS system module first needs to introduce path into the current module.

const path = require('path');

path.join()

Path splicing problem: path separators of different operating systems are not uniform

  • Windows system path separator: \ or/
  • Linux system path separator:/
  • ...


    Actual scenario: the user can upload the avatar on the website. The website developer needs to specify the path for uploading the avatar file to the server, and the function code runs on the Linus system. The path separator is not easy to determine.


    path.join() can solve the problem of path separators. You only need to specify the path name. This method can automatically match the corresponding path separators generated by the system

path.join([...paths])

Function: multiple path fragments can be spliced into a complete path string and returned

Format:

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

Parameter Description:

  • ... Path < string >: sequence of path fragments
  • Return value: < string > spliced path characters

give an example:

const path = require('path');
var pathStr1 = path.join('a', 'b','c');
console.log(pathStr1);
var pathStr2 = path.join('/a','/b/c', '../','./d', 'e');
console.log(pathStr2);
var pathStr3 = path.join(__dirname, './file/1.txt')
console.log(pathStr3);

Operation results



path.basename()

path.basename(path[, ext])
Function: you can obtain the last part of the path, and often obtain the file name in the path through this method.

Format:

path.basename(path[, ext]);

Parameter Description:

  • Path < string >: required, indicating the string of a path
  • Ext < string >: optional, indicating the file extension
  • Return: < string >, indicating the last part of the path

give an example:

const path = require('path');
var fpath = '/a/b/c/index.html';
var fullName = path.basename(fpath);
console.log(fullName); //Output index html
var nameWithoutExt = path.basename(fpath, '.html')
console.log(nameWithoutExt); //Output index

path.extname()

path.extname(path)
Function: get the file extension in the path

Format:

path.extname(path)

Parameter Description:

  • Path < string >: required, indicating a path string
  • Return value: < string > returns the obtained extended name string

give an example:

const path = require('path');
const fpath = '/a/b/c/index.html'; //Path string
const fext = path.extname(fpath);
console.log(fext); //Output html


System module util

util -- node.js API

util.promisify(original)

const fs = require('fs');
// Transform the existing asynchronous function api to return promise object, so as to support asynchronous function syntax
const promisify = require('util').promisify;
// Call the promise method to transform the existing asynchronous API to return the promise object
const readFile = promisify(fs.readFile);

async function run () {
	//The result of the modified readfile asynchronous API (file reading error message object or file reading result) is in the Promise object
	let r1 = await readFile('./1.txt', 'utf8')
	let r2 = await readFile('./2.txt', 'utf8')
	let r3 = await readFile('./3.txt', 'utf8')
	console.log(r1)
	console.log(r2)
	console.log(r3)
}

run();

Keywords: node.js

Added by FadeToLife on Wed, 02 Feb 2022 00:58:46 +0200