search
HomeWeb Front-endJS TutorialNode.js' amazing file operations

Learning points:

Synchronous and asynchronous

Open the file

Get file information

Write the file

Read the file

Close the file

Intercept the file

Delete the file

Create the directory

View the directory

Delete the directory

Node.js file system

Synchronization and asynchronous

Synchronous code is executed from top to bottom, asynchronous code is not controlled by space

Case: file.js

[code]var fs = require('fs');
// 异步读取
fs.readFile('input.txt', function (err, data) {
    if (err)    return console.log(err);
    console.log('异步读取:' + data.toString());
})
// 同步读取
var data = fs.readFileSync('input.txt');
console.log('同步读取:' + data.toString());
console.log('程序执行完毕。');

Node.js amazing file operations

Open file

[code]fs.open(path, flags[, mode], callback)
参数使用说明如下:
    path - 文件的路径。
    flags - 文件打开的行为。
    mode - 设置文件模式(权限),文件创建默认权限为 0666(可读,可写)。
    callback - 回调函数,带有两个参数如:callback(err, fd)。

Case: open.js

[code]var fs = require('fs');
// 异步打开文件
console.log('准备打开文件');
// 读写方式打开inptu.txt
fs.open('input.txt', 'r+', function (err, fd) {
    if (err)    return console.log(err);
    console.log('文件打开成功');
});
console.log('程序执行完毕');

Node.js amazing file operations

Get file information

[code]fs.start(path, callback)
参数使用说明如下:
    path - 文件路径。
    callback - 回调函数,带有两个参数如:(err, stats), stats 是 fs.Stats 对象

Case: info.js

[code]var fs = require('fs');
console.log('准备打开文件');
fs.stat('input.txt', function (err, stats) {
    if (err) return console.error(err);
    console.log(stats);
    console.log('读取文件信息成功');
    // 检测文件类型
    console.log('是否为文件(isFile) ? ' + stats.isFile());
    console.log('是否为目录(isDirectory) ? ' + stats.isDirectory());
})

Node.js amazing file operations

Write file

[code]fs.writeFile(filename, data[, options], callback)
如果文件存在,写入的内容会覆盖旧文件内容
参数使用说明如下:
    path - 文件路径。
    data - 要写入文件的数据,可以是 String(字符串) 或 Buffer(流) 对象。
    options - 该参数是一个对象,包含 {encoding, mode, flag}。默认编码为 utf8, 模式为 0666 , flag 为 'w'
    callback - 回调函数,回调函数只包含错误信息参数(err),在写入失败时返回。

Case: write.js

[code]var fs = require('fs');
console.log('准备写入文件');
fs.writeFile('input.txt', '我是新写入的内容', function (err) {
    if (err) console.error(err);
    console.log('数据写入的数据');
    console.log('-------------------');
});
console.log('读取写入的数据');
fs.readFile('input.txt', function (err, data) {
    if (err) console.error(err);
    console.log('异步读取文件数据:' + data.toString());
})

Node.js amazing file operations

Read file

[code]fs.writeFile(filename, data[, options], callback)
如果文件存在,该方法写入的内容会覆盖旧的文件内容。
参数使用说明如下:
    path - 文件路径。
    data - 要写入文件的数据,可以是 String(字符串) 或 Buffer(流) 对象。
    options - 该参数是一个对象,包含 {encoding, mode, flag}。默认编码为 utf8, 模式为 0666 , flag 为 'w'
    callback - 回调函数,回调函数只包含错误信息参数(err),在写入失败时返回

Case: read.js

[code]var fs = require('fs');
var buf = new Buffer(1024);
fs.open('input.txt', 'r+', function (err, fd) {
    if (err) return console.error(err);
    console.log('文件打开成功');
    console.log('准备读取文件');
    // fd fs.open的标识
    // buf 缓存区
    // 0, buf.length 缓存区区间
    // 0, 读取input.txt开始位置
    fs.read(fd, buf, 0, buf.length, 0, function (err, bytes) {
        if (err) console.log(err);
        console.log(bytes + ' 字节被读取');

        if (bytes > 0) {
            console.log(buf.slice(0, bytes).toString());
        }
    })
})

Node.js amazing file operations

Close file

[code]fs.close(fd, callback)
参数使用说明如下:
    fd - 通过 fs.open() 方法返回的文件描述符。
    callback - 回调函数,没有参数。

Case: close.js

[code]var fs = require('fs');
var buf = new Buffer(1024);
fs.open('input.txt', 'r+', function (err, fd) {
    if (err) return console.error(err);
    console.log('文件打开成功');
    console.log('准备读取文件');
    // fd fs.open的标识
    // buf 缓存区
    // 0, buf.length 缓存区区间
    // 0, 读取input.txt开始位置
    fs.read(fd, buf, 0, buf.length, 0, function (err, bytes) {
        if (err) console.log(err);
        console.log(bytes + ' 字节被读取');

        if (bytes > 0) {
            console.log(buf.slice(0, bytes).toString());
        }
    })
    // 关闭文件 
    fs.close(fd, function (err){
        if (err) console.error(err);
        console.log('文件关闭成功');
    });
})

Node.js amazing file operations

Intercept file

[code]fs.ftruncate(fd, len, callback)
该方法使用了文件描述符来读取文件
参数
    fd - 通过 fs.open() 方法返回的文件描述符。
    len - 文件内容截取的长度。
    callback - 回调函数,没有参数

Case: ftruncate.js

[code]var fs = require('fs');
var buf = new Buffer(1024);
console.log('准备打开文件');
fs.open('input.txt', 'r+', function (err, fd) {
    if (err) return console.error(err);
    console.log('文件打开成功');
    console.log('截取10字节后的文件内容');
    // 截取文件
    fs.ftruncate(fd, 10, function (err) {
        if (err) console.log(err);
        console.log('文件截取成功');
        console.log('读取相同的文件');
        fs.read(fd, buf, 0, buf.length, 0, function (err, bytes) {
            if (err) console.error(err);
            // 仅仅输出读取的字节
            if (bytes > 0) {
                console.log(buf.slice(0, bytes).toString());
            }
            // 关闭文件
            fs.close(fd, function (err) {
                if (err) console.error(err);
                console.log('文件关闭成功');
            })
        })
    })

Node.js amazing file operations

Delete file

[code]fs.unlink(path, callback)
参数
    path - 文件路径
    callback - 回调函数,无参

Case: unlink.js

[code]var fs = require('fs');
console.log('准备删除文件');
fs.unlink('input.txt', function (err) {
    if (err) return console.log(err);
    console.log('文件删除成功');
})

Node.js amazing file operations

Create directory

[code]fs.mkdir(path[, mode], callback)
参数
    path - 文件路径
    mode - 设置目录权限,默认为0777
    callback - 回调函数

Case: mkdir.js

[code]var fs = require('fs');
console.log('创建目录 test');
fs.mkdir('test', function (err) {
    if (err) return console.error(err);
    console.log('目录创建成功');
});

Node.js amazing file operations

View directory

[code]fs.readdir(path, callback)
参数使用说明如下:
    path - 文件路径。
    callback - 回调函数,回调函数带有两个参数err, files,err 为错误信息,files 为 目录下的文件数组列表

Case: readdir.js

[code]var fs = require('fs');
console.log('查看 /file 目录');
fs.readdir('../file/', function (err, files) {
    if (err) return console.log(err);
    files.forEach(function (file) {
        console.log(file);
    })
})

Node.js amazing file operations

Delete directory

[code]fs.rmdir(path, callback)
参数使用说明如下:
    path - 文件路径。
    callback - 回调函数,没有参数。

Case: rmdir.js

[code]var fs = require('fs');
console.log('删除 /test 目录');
fs.rmdir('test', function (err){
    if (err) console.error(err);
    console.log('读取 /test 目录');
    fs.readdir('test', function (err, files) {
        if (err) return console.log(err);
        files.forEach(function (file) {
            console.log(file);
        })
    })
});

Node.js amazing file operations

The above is the content of Node.js’ amazing file operations. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!


Statement
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
The Origins of JavaScript: Exploring Its Implementation LanguageThe Origins of JavaScript: Exploring Its Implementation LanguageApr 29, 2025 am 12:51 AM

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

Behind the Scenes: What Language Powers JavaScript?Behind the Scenes: What Language Powers JavaScript?Apr 28, 2025 am 12:01 AM

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The Future of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Python vs. JavaScript: Development Environments and ToolsPython vs. JavaScript: Development Environments and ToolsApr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript's Role: Making the Web Interactive and DynamicJavaScript's Role: Making the Web Interactive and DynamicApr 24, 2025 am 12:12 AM

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C   and JavaScript: The Connection ExplainedC and JavaScript: The Connection ExplainedApr 23, 2025 am 12:07 AM

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

See all articles

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

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function