Home > Article > Web Front-end > Learn about folder writing in Node.js
This article will introduce to you the folder writing in Node.js. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.
Related recommendations: "node js tutorial"
fs.Dir is the class of an iterable directory stream, fs.Dirent is the directory item obtained by traversing fs.Dir, which can be a file or a subdirectory in the directory
fs.opendir(path[, options], callback)
Open a directory and return fs.Dir Object
const fs = require('fs/promises'); async function print(path) { const dir = await fs.opendir(path); for await (const dirent of dir) { console.log(dirent.name); } } print('./').catch(console.error);
can iterate dir
const fs = require('fs/promises'); async function print(path) { const dir = await fs.opendir(path); let dirent = await dir.read(); while (dirent) { console.log(dirent.name); dirent = await dir.read(); } dir.close(); } print('./').catch(console.error);
fs.readdir(path[, options], callback)
Read the contents of the directory. The callback has two parameters (err, files), where files is an array of file names in the directory (excluding '.' and '..')
options
const fs = require('fs/promises'); async function print(path) { const files = await fs.readdir(path); for (const file of files) { console.log(file); } } print('./').catch(console.error);
fs.mkdir(path[, options], callback)
Create directory
options
mkdir -p
will create a directory that does not exist. // 创建 /tmp/a/apple 目录,无论是否存在 /tmp 和 /tmp/a 目录。 fs.mkdir('/tmp/a/apple', { recursive: true }, err => { if (err) throw err; });
fs.rmdir(path[, options], callback)
fs.rmdir is used to delete folders
options
const fs = require('fs'); fs.rmdir('./tmp', { recursive: true }, err => console.log);
Before, rmdir could only delete empty folders, but now it can delete them together with files
More For programming related knowledge, please visit: Programming Teaching! !
The above is the detailed content of Learn about folder writing in Node.js. For more information, please follow other related articles on the PHP Chinese website!