nodeJs file system (fs) and stream

File System:

  1. In Node, file system interaction is very important. The essence of server is to send local files to client,
  2. Node interacts with the file system through fs module, which provides some standard file access API classes to open, read, write files, and interact with them.
  3. If you use FS module, first load it from the core module; use const fs= require('fs'); to import

fs features:

  1. There are two types of operations in the fs module: synchronous and asynchronous,
  2. Synchronizing the file system blocks the execution of the program, which means that the code will not be executed downward until the operation is completed.
  3. The asynchronous file system does not block the execution of the program, but returns the result through the callback function when the operation is completed.
//1 \. Import module
const fs= require("fs");
// console.log(fs)

//2 \. Open file
// fs.open asynchronous read (usually asynchronous needs to set callback function)  
// fs.openSync synchronous read (thread will be blocked when reading)

let hello = fs.openSync("hello.txt", "w");
//                     Automatically create if it does not exist

//3 \. Write content
fs.writeFileSync(hello,'hello word!');

//4 \. Save and exit
fs.closeSync(hello);

[](https://github.com/AnsonZnl/S...

File operation:

  1. Open file:

fs.open(path,flags[,mode],callback)
Asynchronously open asynchronously are all callback nested callbacks
fs.openSync(path,flags[,mode])
Synchronous opening

File flags: http://nodejs.cn/api/fs.html#fs_fs_open_path_flags_mode_callback

I. open files synchronously

    //1 \. Import module 
    let fs = require('fs');

    //2. Open file synchronization
    var fd=fs.openSync('1.txt', 'w');

    //3. Write content
    fs.writeFileSync(fd,"hello world!"); 

    //4 \. Save and close
    fs.closeSync(fd);

II. Asynchronous file opening

   //1. Introduction module
   let fs = require('fs');

   //2 \. Open file
   fs.open('1.txt', 'a', (err, fd)=>{
       //2.1 judge whether there is error
       if(!err){
           //Correct 2.2 write file
           fs.writeFile(fd, "Today's Day.....Good breath!", (err)=>{
                //2.2.1 write succeeded
                if(!err){
                    console.log('Write successfully');
                }else{
                    throw err;
                }
                //2.3 closing documents
                fs.close(fd, (err)=>{
                    if(!err){
                        console.log('File to save and close')
                    }else{
                        throw err;
                    }
                })
           })
       }else{
           throw err;
       }
   })

[](https://github.com/AnsonZnl/S...

Write using FileStream

FileStream write: http://nodejs.cn/api/fs.html#fs_fs_createwritestream_path_options

//Synchronous operation

//1 \. Import module
let fs= require('fs');

//2. Establish channels
let ws = fs.createWriteStream('fsw.txt')

//3. Open the channel
ws.once('open', ()=>{
    console.log('Channel already open');
})

ws.once('close', ()=>{
    console.log('Channel closed');
})

//4 \. Write content
ws.write('I love you!');
ws.write('I love you!');
ws.write('I love you!');

[](https://github.com/AnsonZnl/S...

Read write file:

Document address: http://nodejs.cn/api/fs.html#fs_fs_readfile_path_options_callback
Read document:

//1 \. Import module
let fs = require('fs');

//2 \. Read file
fs.readFile('source/hello.txt','utf8',(err,data)=>{
    //Judge success
    if(!err){
        console.log(data);//
        // console.log(data.toString());
        //The default read of data is binary, which is converted to
    }else{
        throw err;
    }
})

//Read picture:

//3 \. Read picture
fs.readFile("source/psb.jpg",(err,data)=>{
    //Judge success
    if(!err){
        //Writing picture
        fs.writeFile('img.jpg', data, (err)=>{
            if(!err){
                console.log('Write succeeded!')
            }else{
                throw err;
            }
        })
    }else{
        throw err;
    }
});

[](https://github.com/AnsonZnl/S...

Read video:

//1 \. Import module
let fs= require('fs');

//2 \. Read video
fs.readFile('source/cddbb.mp4', (err, data)=>{
    if(!err){
        // Write video
        fs.writeFile('nmx.mp4', data, (err)=>{
            if(!err){
                console.log('Write succeeded!');
            }else{
                throw err;
            }
        })
    }else{
        throw err;
    }
})

//3 \. Read in of streaming files (batch file processing)
let re= fs.createReadStream('source/cddbb.mp4');
//Create read stream
let ws= fs.createWriteStream('New video.mp4');
//Create write stream

//4 \. Create pipe
re.pipe(ws);//File streaming
console.log('File stream transfer complete')

Reference resources: Detailed explanation of NodeJS file system fs
My GitHub concludes NodeJS notes

Keywords: node.js github

Added by emorr1981 on Mon, 09 Dec 2019 09:18:24 +0200