Home > Web Front-end > JS Tutorial > body text

Synchronous and asynchronous implementation of file system in Node.js

不言
Release: 2018-08-23 17:19:28
Original
1461 people have browsed it

The content of this article is about the implementation of synchronization and asynchronousness of the file system in Node.js. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

1. Synchronous and asynchronous

All methods have asynchronous and synchronous forms;

The last parameter of an asynchronous method is a callback function. The parameters passed to the callback function depend on the specific method, but the first parameter of the callback function is reserved for exceptions. If the operation completes successfully, the first parameter will be null or undefined.

Example: Directory fs/fs-1.js:

//导入fs模块
const fs = require('fs');
// 同步和异步
//  ============例子1:实现重命名文件 rename()==========
// 异步方法
fs.rename('./text.txt', 'hello.txt', function (err) {
    if (err) throw err;
    console.log('异步重命名成功');
})
// 同步方法
fs.renameSync('./hello.txt','zhang.txt');
console.log('同步重命名成功');


 例子2:新建目录  mkdir(),并修改目录名称==========
fs.mkdir('test',function (err) {
    if(err) throw  err;
    // 重命名目录名称
    fs.rename('./test','./new',function (err) {
        if(err) throw err;
        console.log("目录创建并重命名成功");
    })
});
Copy after login

Related recommendations:

Node. Detailed introduction to global objects in js

Implementation code of router control in Node.js

The above is the detailed content of Synchronous and asynchronous implementation of file system in Node.js. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source: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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!