This is the 9th day of my participation in the November Gwen Challenge. Check out the event details: The last Gwen Challenge 2021

Fs file system

You can use the FS module in Node to perform operations such as reading and writing files. The best way to learn about the FS file system module is to look at the official API

Official website: nodejs.cn/api/fs.html…

Fs has encapsulated methods for reading and writing files. These methods are also divided into synchronous and asynchronous reads and writes (generally asynchronous reads and writes are used for operation).

Read/write file operations

Read readFileSync synchronously

parameter instructions
path File name or file descriptor (including file path)
options Flag: the default value is ‘r’ read-only. Encoding: Encoding format

The options parameter is included by [], and the parameter wrapped by [] is optional

Example:

const fs = require('fs');
let contant = fs.readFileSync('. The/file 1. TXT ', { flag: 'r'.encoding:'utf-8' });
Copy the code

Read readFile asynchronously

Fs.readfile (path[, options], callback)

And in the callback function, the first parameter is err error information, because the asynchronous execution is divided into two segments, and the program cannot directly capture the exception and error thrown between the two segments, but can only pass the second segment as parameters

Example:

contant = fs.readFile(path, { flag: 'r'.encoding:'utf-8' }, (err, data) = > {
    if (err) {
    }
}); 
Copy the code

If you need to read multiple files, using nested methods to read can easily create callback hell, so use Promise, Async, await to wrap writing

In the following readList, the contents of the previous file get the name of the file to be read next time

// Encapsulate method
function getFile(path) {
    return new Promise((resolve, reject) = >{
        contant = fs.readFile(path, { flag: 'r'.encoding:'utf-8' }, (err, data) = > {
            if(err) { reject(err); } resolve(data); }); })}async function readList() {
    let res1 = await getFile('. The/file 1. TXT ');
    let res2 = await getFile(`${res1}.txt`);
    let res3 = await getFile(`${res2}.txt`);
    console.log(res3);
}
Copy the code

Files are written to writeFile

With file reading, there is of course file writing, so I won’t cover synchronous writing to writeFileSync here

The writeFile method takes four parameters

parameter instructions
file File name or file descriptor (including file path)
data The content that needs to be written to the file
options Flag: the default value is ‘w’. Encoding: indicates the encoding format. Mode: indicates that no change is required
callback Callback function for asynchronous write operations

Example: You can also use Promise, async, await to avoid writing callback hell

function writeFun(path, content, flag = 'a') {
    return new Promise((resolve, reject) = >{
        fs.writeFile(path, content, { flag: flag, encoding:'utf-8' }, (err) = >{
            if (err) {
                reject(err);
            } else {
                resolve('Write succeeded'); }})})}async function wirteList() {
    writeFun('./k.html'.' '.'w'); // Clear the contents of the file
    await writeFun('./k.html'.1. Current memory \n');
    await writeFun('./k.html'.2. Current memory \n');
    await writeFun('./k.html'.'

3. Current memory

\n'
); await writeFun('./k.html'.'

4. Current memory

); } Copy the code

Example Delete the unlink of a file

If the file is no longer needed, you can delete it using the Unlink method

Asynchronous unlink deletion has only two parameters, path and callback

function deleteFile(path) {
    return new Promise((resolve, reject) = >{
        fs.unlink(path, (err) = >{
            if (err) {
                reject('Delete failed');
            } else {
                resolve('Deleted successfully'); }})})}Copy the code

In addition to these methods, there are mkdir and RMdir for directory operations, in addition to other things, of course, most of these content can be mastered or usually need to write and read more API


Readline reads line by line

The readline module provides an interface for reading data one line at a time from a readable stream, such as process.stdin.

In the following example, input and output represent input and output

const readline = require('readline');

let rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
})
Copy the code

Input information can be written using the Question method

rl.question('Start typing? '.(answer) = >{
    console.log('My input:${answer}`);
    rl.pause();  // Pause the input stream
    // rl.close(); // Close the instance and relinquish control over the input and output streams
})
// on listen, trigger pause method
rl.on('pause'.() = >{
    console.log('Readline paused.');
})
Copy the code

Effect:

If you need to enter multiple commands, you can encapsulate the question.

Readline allows simple interaction with Nodes on the terminal

Example: This is an example of storing multiple messages in TXT

function inputQue(question) {
    return new Promise((resolve, reject) = >{
        rl.question(question, (answer) = >{ resolve(answer); })})}async function quesList() {
    let name = await inputQue('Your name is:');
    let age = await inputQue('Your age is:');
    let sex = await inputQue('Your gender is:');
    let money = await inputQue('Your deposit amount is:');

    let str = ` name:${name}Years of age:${age}Don't:${sex}Kim:${money}Yuan `
    writeFun('./new.txt', str, 'a');  // writeFun is the file writing method above
    rl.close();  
}

quesList();
Copy the code

Effect:

Little knowledge:

If readline is still not convenient enough, you can use Inquirer, a collection of tools for implementing command-line interactive interfaces. Installation: YARN Add Inquirer

Example login using inquirer

const inquirer = require('inquirer')

var questions = [
  {
    type: 'input'.name: 'name'.message: "Your username?".default: 'kcj'}, {type: 'password'.name: 'password'.message: "Your password?".mask: true.By returning true, the callback function passes two arguments, the first one the user entered, and the second one the answers to all previous sessions
    validate: (val, proval) = >{
        if(val ! ='123') { return 'Your password is wrong, please try again'; }
        else {
            return true; }}}]function verificate() {
    return inquirer.prompt(questions).then(answers= > {
        if (answers['name'] = ='kcj')
            console.log(Hello `${answers['name']}! \n Welcome to login);
        else {
            console.log('Your account does not exist, please try again');
            return verificate();  // Start the verification again from the input user name}})}Copy the code

The effect: Input correctly

Input error

flow

Writing and reading of file contents can also be considered in the form of streams

In general, for small files, reading and writing can be done directly using readFile and writeFile above.

However, fs.createReadStream and fs.createWriteStream are still required for large files