Home Web Front-end JS Tutorial Detailed introduction to Fs module in NodeJs (code example)

Detailed introduction to Fs module in NodeJs (code example)

Jan 11, 2019 am 11:27 AM
node.js

This article brings you a detailed introduction (code example) about the Fs module in NodeJs. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Fs module

  1. fs.stat detects whether it is a file or directory

//目录
fs.stat('html', function(err, stats) {
    if (err) {
        console.log(err);
        return false;
    }
    console.log('文件:' + stats.isFile());
    console.log('目录:' + stats.isDirectory());
})
//文件
fs.stat('index.txt', function(err, stats) {
    if (err) {
        console.log(err);

        return false;
    }
    console.log('文件:' + stats.isFile());
    console.log('目录:' + stats.isDirectory());
})
Copy after login

2.fs.mkdir Create directory

//接收参数:
//path          将创建的目录路径
//mode          目录权限(读写权限),默认0777
//callback      回调,传递异常参数err
fs.mkdir('css', function(err) {
    if (err) {
        console.log(err);
        return false;
    }
    console.log('创建目录成功');
})
Copy after login

3.fs.writeFile Create write file

//filename      (String)           文件名称
//data          (String | Buffer)  将要写入的内容,可以使字符串 或 buffer数据。
//options       (Object)           option数组对象,包含:
//· encoding    (string)           可选值,默认 ‘utf8′,当data使buffer时,该值应该为 ignored。
//· mode        (Number)           文件读写权限,默认值 438
//· flag        (String)           默认值 ‘w'
//callback {Function}              回调,传递一个异常参数err。

fs.writeFile('t.txt', '你好nodejs 覆盖', 'utf8', function(err) {
    if (err) {
        console.log(err);
        return false;
    }
    console.log('写入成功');
})
Copy after login

4.fs.appendFile Append file

fs.appendFile('t1.txt', '这是写入的内容', function(err) {
    if (err) {
        console.log(err);
        return false;
    }
    console.log('写入成功');
})
Copy after login

5.fs.readFile Read file

fs.readFile('t1.txt', function(err, data) {
    if (err) {
        console.log(err);
        return false;
    }
    //console.log(data);
    console.log(data.toString());
})
Copy after login

6.fs.readdir Read directory

fs.readdir('html', function(err, data) {
    if (err) {
        console.log(err);
        return false;
    }
    console.log(data);
})
Copy after login

7.fs.rename Rename

// 1. 改名 2. 剪切文件
fs.rename('html/index.html', 'html/news.html', function(err) {
    if (err) {
        console.log(err);
        return false;
    }
    console.log('修改名字成功');
})
Copy after login

8.fs.rmdir Delete Directory

fs.rmdir('t', function(err) {
    if (err) {
        console.log(err);
        return false;
    }
    console.log('删除目录成功');
})

// ENOENT: no such file or directory, rmdir      rmdir 这个方法只能删除目录
fs.rmdir('index.txt', function(err) {
    if (err) {
        console.log(err);
        return false;
    }
    console.log('删除目录成功');
})
Copy after login

9.fs.unlink Delete file

fs.unlink('index.txt', function(err) {
    if (err) {
        console.log(err);
        return false;
    }
    console.log('删除文件成功');
})
Copy after login

10.fs.createReadStream Read data from file stream

const fs = require('fs')
    //流的方式读取文件
let readStream = fs.createReadStream('input.txt');
let str = ''; /*保存数据*/
let count = 0; /*次数*/
readStream.on('data', function(chunk) {
        str += chunk;
        count++;
    })
    //读取完成
readStream.on('end', function(chunk) {
        console.log(count);
        console.log(str);
    })
    //读取失败
readStream.on('error', function(err) {
    console.log(err);
})
Copy after login

11.fs.createWriteStream Write file

let fs = require("fs");
let data = '我是从数据库获取的数据,我要保存起来11\n';
// 创建一个可以写入的流,写入到文件 output.txt 中
let writerStream = fs.createWriteStream('output.txt');
for (let i = 0; i < 100; i++) {
    writerStream.write(data, 'utf8');
}
//标记写入完成
writerStream.end();
writerStream.on('finish', function() {
        console.log('写入完成');
    })
    //失败
writerStream.on('error', function() {
    console.log('写入失败');
})
Copy after login

12. Pipe flow

let fs = require("fs");
// 创建一个可读流
let readerStream = fs.createReadStream('input.txt');
// 创建一个可写流
let writerStream = fs.createWriteStream('output.txt');
// 管道读写操作
// 读取 input.txt 文件内容,并将内容写入到 output.txt 文件中
readerStream.pipe(writerStream);
console.log("程序执行完毕");
Copy after login

The above is the detailed content of Detailed introduction to Fs module in NodeJs (code example). For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1662
14
PHP Tutorial
1262
29
C# Tutorial
1235
24
Detailed graphic explanation of the memory and GC of the Node V8 engine Detailed graphic explanation of the memory and GC of the Node V8 engine Mar 29, 2023 pm 06:02 PM

This article will give you an in-depth understanding of the memory and garbage collector (GC) of the NodeJS V8 engine. I hope it will be helpful to you!

An article about memory control in Node An article about memory control in Node Apr 26, 2023 pm 05:37 PM

The Node service built based on non-blocking and event-driven has the advantage of low memory consumption and is very suitable for handling massive network requests. Under the premise of massive requests, issues related to "memory control" need to be considered. 1. V8’s garbage collection mechanism and memory limitations Js is controlled by the garbage collection machine

Let's talk about how to choose the best Node.js Docker image? Let's talk about how to choose the best Node.js Docker image? Dec 13, 2022 pm 08:00 PM

Choosing a Docker image for Node may seem like a trivial matter, but the size and potential vulnerabilities of the image can have a significant impact on your CI/CD process and security. So how do we choose the best Node.js Docker image?

Node.js 19 is officially released, let's talk about its 6 major features! Node.js 19 is officially released, let's talk about its 6 major features! Nov 16, 2022 pm 08:34 PM

Node 19 has been officially released. This article will give you a detailed explanation of the 6 major features of Node.js 19. I hope it will be helpful to you!

Let's talk in depth about the File module in Node Let's talk in depth about the File module in Node Apr 24, 2023 pm 05:49 PM

The file module is an encapsulation of underlying file operations, such as file reading/writing/opening/closing/delete adding, etc. The biggest feature of the file module is that all methods provide two versions of **synchronous** and **asynchronous**, with Methods with the sync suffix are all synchronization methods, and those without are all heterogeneous methods.

Let's talk about the event loop in Node Let's talk about the event loop in Node Apr 11, 2023 pm 07:08 PM

The event loop is a fundamental part of Node.js and enables asynchronous programming by ensuring that the main thread is not blocked. Understanding the event loop is crucial to building efficient applications. The following article will give you an in-depth understanding of the event loop in Node. I hope it will be helpful to you!

Let's talk about how to use pkg to package Node.js projects into executable files. Let's talk about how to use pkg to package Node.js projects into executable files. Dec 02, 2022 pm 09:06 PM

How to package nodejs executable file with pkg? The following article will introduce to you how to use pkg to package a Node project into an executable file. I hope it will be helpful to you!

What should I do if node cannot use npm command? What should I do if node cannot use npm command? Feb 08, 2023 am 10:09 AM

The reason why node cannot use the npm command is because the environment variables are not configured correctly. The solution is: 1. Open "System Properties"; 2. Find "Environment Variables" -> "System Variables", and then edit the environment variables; 3. Find the location of nodejs folder; 4. Click "OK".

See all articles