Home Web Front-end JS Tutorial Parsing NodeJs's fs read, write, delete and move monitoring

Parsing NodeJs's fs read, write, delete and move monitoring

Apr 30, 2017 am 11:08 AM
javascript nodejs

This article mainly introduces the fs read, write, delete and mobile monitoring of NodeJs. It is very good and has reference value. Friends in need can refer to it

NodeJs version: 4.4.4

fs

The file system module is a collection that encapsulates standard POSIX file I/O operations. Methods in the Node.js Filesystem (fs module) module have both asynchronous and synchronous versions.

Copy and paste pictures

Create a readable stream and a write stream. via pipe.

var fileReadStream = fs.createReadStream(sourcePath);
var fileWriteStream = fs.createWriteStream(targetPath);
fileReadStream.pipe(fileWriteStream);
//监听关闭事件得知执行完成
fileWriteStream.on('close', function() {
 console.log('移动成功!');   
})
Copy after login

Read file (fs.readFile)

Definition: fs.readFile( filename[, options], callback)

Parameters:

  • filename:{String} file name/file path

  • options:{Object} Optional parameters

encoding:{String | Null} Default = null Encoding method

flag:{String} Default = 'r' File opening behavior (writable, readable, etc.)

  • callback:{Function}

var fs = require('fs');
//读取文件
fs.readFile('../lianxi/child_process.js',{
 encoding:'utf-8',
 flag:'r'
}, function(err,data){
 if(err) throw err;
 console.log(data);
});
Copy after login

If the encoding method is not set when reading files here, the read files will be returned in the form of buffer.

<Buffer 76 61 72 20 63 68 69 6c 64 5f 70 72 6f 63 65 73 73 20 3d 20 72 65 71 75 69 72 65 28 27 63 68 69 6c 64 5f 70 72 6f 63 65 73 73 27 29 3b 0d 0a 76 61 72 ... >
Copy after login

After setting to utf-8, the returned value is in the form of a string. As follows:

var child_process = require(&#39;child_process&#39;);...
Copy after login

Write file (fs.writeFile)

Definition :fs.writeFile(filename, data[, options], callback)

Parameters:

  • filename:{String}

  • data:{String | Buffer}

  • options:{Object}

##encoding:{ String | Null} Default = 'utf8'

mode:{Number} Default = 438 (aka 0666 in Octal)
flag:{String} Default = 'w'

  • callback {Function}


//写入文件
fs.writeFile(&#39;../lianxi/child_process.js&#39;,&#39;[zqz]要写入的数据字符串或者buffer&#39;,{
 encoding:&#39;utf8&#39;,
 mode:438,
 flag:&#39;w&#39;
},function(err){
})
Copy after login

Note: Write the file asynchronously, replacing the file if it already exists.

Open file (fs.open)

Definition: fs.open(path, flags[, mode], callback)

Parameters:

  • path: file/file path

  • flags: file opening behavior

  • mode: Set the file mode (permissions). The default permissions for file creation are 0666 (readable, writable).

  • callback: callback function


//打开文件
fs.open(&#39;../lianxi/child_process.js&#39;,&#39;r+&#39;,0666,function(err,data){
})
Copy after login

Add data to the file (fs.appendFile)

Definition: fs.appendFile(filename, data[, options], callback)

Parameters:

  • filename:{String}


  • data:{String | Buffer}


  • options :{Object}


encoding {String | Null} Default = 'utf8'

mode {Number} Default = 438 (aka 0666 in Octal)
flag {String} default = 'a'

    ##callback {Function}

//给文件添加数据
fs.appendFile(&#39;../lianxi/child_process.js&#39;, &#39;异步添加的字符串或buffer&#39;, {
 encoding:&#39;utf8&#39;,
 mode:438,
 flag:&#39;a&#39;
}, function(err){
});
Copy after login

Note:Add data to the file asynchronously. If the file does not exist, a file will be created.

Delete file (fs.unlink)Definition: fs.unlink(path, callback)

var fs = require(&#39;fs&#39;);
fs.unlink(&#39;./t/index.html&#39;,function (err) {
 if(err) throw err;
 console.log(&#39;成功&#39;)
})
Copy after login


Create file (fs.open)Definition: fs.open( path, flags[, mode], callback)

You can also use fs.open to create files.

fs.open("test.txt", "w",function (err) {
});
Copy after login


##Delete folder (fs.rmdir)

Definition: fs.rmdir(path, callback)

fs.rmdir(&#39;./t/a&#39;,function (err) {
 if(err) throw err;
 console.log(&#39;成功&#39;)
})
Copy after login


Create file Folder (fs.mkdir)

Definition: fs.mkdir(path[, mode], callback)

Parameter: mode The default is to 0777.

fs.mkdir(&#39;./t/a&#39;,0777,function (err) {
 if(err) throw err;
 console.log(&#39;成功&#39;)
})
Copy after login

File monitoring (fs.watch fs.watchFile)

Definition: fs.watch(filename [, options][, listener])Definition: fs.watchFile(filename[, options], listener)


fs.watch(&#39;test.js&#39;, function (event, filename) {
});
fs.watchFile(&#39;test.js&#39;, function(curr, prev){
});
Copy after login

flags


##rOpen in read mode document. Throws an exception if the file does not exist. r+Open the file in read-write mode. Throws an exception if the file does not exist. rs Read files synchronously. rs+ Read and write files synchronously. wOpen the file in writing mode, creating it if it does not exist. wxLike 'w', but if the file path exists, file writing fails.
Flag Description
w+ Open the file in read-write mode and create it if it does not exist.
wx+ Similar to 'w+', but if the file path exists, file reading and writing will fail.
a Open the file in append mode, creating it if it does not exist.
ax Similar to 'a', but if the file path exists, file appending fails.
a+ Open the file in read-append mode, creating it if it does not exist.
ax+ Similar to 'a+', but if the file path exists, file reading and appending will fail.


The above is the detailed content of Parsing NodeJs's fs read, write, delete and move monitoring. 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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

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)

Is nodejs a backend framework? Is nodejs a backend framework? Apr 21, 2024 am 05:09 AM

Node.js can be used as a backend framework as it offers features such as high performance, scalability, cross-platform support, rich ecosystem, and ease of development.

How to connect nodejs to mysql database How to connect nodejs to mysql database Apr 21, 2024 am 06:13 AM

To connect to a MySQL database, you need to follow these steps: Install the mysql2 driver. Use mysql2.createConnection() to create a connection object that contains the host address, port, username, password, and database name. Use connection.query() to perform queries. Finally use connection.end() to end the connection.

What is the difference between npm and npm.cmd files in the nodejs installation directory? What is the difference between npm and npm.cmd files in the nodejs installation directory? Apr 21, 2024 am 05:18 AM

There are two npm-related files in the Node.js installation directory: npm and npm.cmd. The differences are as follows: different extensions: npm is an executable file, and npm.cmd is a command window shortcut. Windows users: npm.cmd can be used from the command prompt, npm can only be run from the command line. Compatibility: npm.cmd is specific to Windows systems, npm is available cross-platform. Usage recommendations: Windows users use npm.cmd, other operating systems use npm.

What are the global variables in nodejs What are the global variables in nodejs Apr 21, 2024 am 04:54 AM

The following global variables exist in Node.js: Global object: global Core module: process, console, require Runtime environment variables: __dirname, __filename, __line, __column Constants: undefined, null, NaN, Infinity, -Infinity

Is there a big difference between nodejs and java? Is there a big difference between nodejs and java? Apr 21, 2024 am 06:12 AM

The main differences between Node.js and Java are design and features: Event-driven vs. thread-driven: Node.js is event-driven and Java is thread-driven. Single-threaded vs. multi-threaded: Node.js uses a single-threaded event loop, and Java uses a multi-threaded architecture. Runtime environment: Node.js runs on the V8 JavaScript engine, while Java runs on the JVM. Syntax: Node.js uses JavaScript syntax, while Java uses Java syntax. Purpose: Node.js is suitable for I/O-intensive tasks, while Java is suitable for large enterprise applications.

Is nodejs a back-end development language? Is nodejs a back-end development language? Apr 21, 2024 am 05:09 AM

Yes, Node.js is a backend development language. It is used for back-end development, including handling server-side business logic, managing database connections, and providing APIs.

How to deploy nodejs project to server How to deploy nodejs project to server Apr 21, 2024 am 04:40 AM

Server deployment steps for a Node.js project: Prepare the deployment environment: obtain server access, install Node.js, set up a Git repository. Build the application: Use npm run build to generate deployable code and dependencies. Upload code to the server: via Git or File Transfer Protocol. Install dependencies: SSH into the server and use npm install to install application dependencies. Start the application: Use a command such as node index.js to start the application, or use a process manager such as pm2. Configure a reverse proxy (optional): Use a reverse proxy such as Nginx or Apache to route traffic to your application

Which one to choose between nodejs and java? Which one to choose between nodejs and java? Apr 21, 2024 am 04:40 AM

Node.js and Java each have their pros and cons in web development, and the choice depends on project requirements. Node.js excels in real-time applications, rapid development, and microservices architecture, while Java excels in enterprise-grade support, performance, and security.

See all articles