Home Web Front-end JS Tutorial Node.js' amazing file operations

Node.js' amazing file operations

Jan 17, 2017 pm 04:05 PM

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('程序执行完毕。');
Copy after login

Node.js amazing file operations

Open file

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

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('程序执行完毕');
Copy after login

Node.js amazing file operations

Get file information

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

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());
})
Copy after login

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),在写入失败时返回。
Copy after login

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());
})
Copy after login

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),在写入失败时返回
Copy after login

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());
        }
    })
})
Copy after login

Node.js amazing file operations

Close file

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

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('文件关闭成功');
    });
})
Copy after login

Node.js amazing file operations

Intercept file

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

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('文件关闭成功');
            })
        })
    })
Copy after login

Node.js amazing file operations

Delete file

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

Case: unlink.js

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

Node.js amazing file operations

Create directory

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

Case: mkdir.js

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

Node.js amazing file operations

View directory

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

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);
    })
})
Copy after login

Node.js amazing file operations

Delete directory

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

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);
        })
    })
});
Copy after login

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 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)

How to safely read and write files using Golang? How to safely read and write files using Golang? Jun 06, 2024 pm 05:14 PM

Reading and writing files safely in Go is crucial. Guidelines include: Checking file permissions Closing files using defer Validating file paths Using context timeouts Following these guidelines ensures the security of your data and the robustness of your application.

Go Programming Tips: Deleting Contents from a File Go Programming Tips: Deleting Contents from a File Apr 04, 2024 am 10:06 AM

The Go language provides two methods to clear file contents: using io.Seek and io.Truncate, or using ioutil.WriteFile. Method 1 involves moving the cursor to the end of the file and then truncating the file, method 2 involves writing an empty byte array to the file. The practical case demonstrates how to use these two methods to clear content in Markdown files.

Can I delete gho files? Can I delete gho files? Feb 19, 2024 am 11:30 AM

A gho file is an image file created by NortonGhost software and used to back up and restore the operating system and data. In some cases, you can delete gho files, but do so with caution. This article will introduce the role of gho files, precautions for deleting gho files, and how to delete gho files. First, let's understand the role of gho files. A gho file is a compressed system and data backup file that can save an image of an entire hard disk or a specific partition. This kind of backup file is usually used for emergency recovery

How to fix: Java file operation error: File write failed How to fix: Java file operation error: File write failed Aug 26, 2023 pm 09:13 PM

How to solve: Java file operation error: File writing failed. In Java programming, you often encounter the need for file operations, and file writing is one of the important functions. However, sometimes we encounter file writing failure errors, which may prevent the program from running properly. This article will describe some common causes and solutions to help you solve this type of problem. Wrong path: A common problem is wrong file path. When we try to write a file to the specified path, if the path does not exist or the permissions are insufficient, the file will be written.

PHP file operation example: reading CSV file PHP file operation example: reading CSV file Jun 20, 2023 am 11:42 AM

PHP is a popular programming language widely used in web development. In web applications, file operations are a basic and common function. This article will explain how to use PHP to read a CSV file and display it in an HTML table. CSV is a common file format used to import tabular data into spreadsheet software such as Excel. CSV files usually consist of many lines, each line consisting of comma separated values. The first line usually contains column headers, which describe the meaning of each column value. Here we will use PHP

How to insert content at a specified location in a file using C++? How to insert content at a specified location in a file using C++? Jun 04, 2024 pm 03:34 PM

In C++, use the ofstream class to insert content at a specified location in a file: open the file and locate the insertion point. use

Learn the file operation functions in Go language and implement the encryption, compression, upload and download functions of files Learn the file operation functions in Go language and implement the encryption, compression, upload and download functions of files Jul 29, 2023 pm 10:37 PM

Learn the file operation functions in Go language and implement the encryption, compression, upload and download functions of files. Go language is an open source statically typed programming language. It is widely popular in the development field for its efficient performance and concise syntax. The standard library of the Go language provides a wealth of file operation functions, making it very simple to read and write files, encrypt and compress them, upload and download them. This article will introduce how to use the file operation functions in the Go language to implement the functions of encrypting, compressing, uploading and downloading files. First, we need to import the relevant three

How to use SplFileInfo for file operations in php? How to use SplFileInfo for file operations in php? Jun 01, 2023 pm 07:01 PM

As a widely used server-side programming language, PHP not only provides many convenient file processing functions, but also provides some more advanced file operation classes. One of the more useful classes is SplFileInfo, which allows us to perform file reading and writing operations more flexibly and efficiently. This article will introduce how to use the SplFileInfo class in PHP for file operations. 1. Overview of SplFileInfo class SplFileInfo class is a built-in class in PHP (no need

See all articles