如何使用 Node.js 获取 Web 服务器目录中存在的所有文件的名称列表?
How do you get a list of the names of all files present in a web server directory using Node.js?
当使用 fs.readdir 时,它会给出给定路径中的文件名,但如何获取存储在 Web 服务器上特定路径上的文件名。
我相信你正在使用这个功能
fs.readdir ('../', function (err, data) {
if (err) console.log(err, err.stack); // an error occurred
else console.log(data); // successful response
});
访问
- root(或C盘)使用
/
.
- 当前目录使用
./
.
- 父目录使用
../
.
- 父目录的父目录使用
../../
.
- 要访问父目录中的目录,请使用
../sibling_name
。
现在我相信您可以浏览目录了。浏览目录并列出目录中包含的文件和文件夹。
我想这对你有帮助。
const fs = require('fs');
const path = require('path');
function getFile(dirPath) {
const files = fs.readdirSync(dirPath);
files.forEach(function (item) {
const currentPath = path.join(dirPath, item),
isFile = fs.statSync(currentPath).isFile(),
isDir = fs.statSync(currentPath).isDirectory();
if (isFile) {
// console.log(currentPath);
} else if (isDir) {
console.log(currentPath);
getFile(currentPath);
}
});
}
getFile('./'); // this is your server path
当使用 fs.readdir 时,它会给出给定路径中的文件名,但如何获取存储在 Web 服务器上特定路径上的文件名。
我相信你正在使用这个功能
fs.readdir ('../', function (err, data) {
if (err) console.log(err, err.stack); // an error occurred
else console.log(data); // successful response
});
访问
- root(或C盘)使用
/
. - 当前目录使用
./
. - 父目录使用
../
. - 父目录的父目录使用
../../
. - 要访问父目录中的目录,请使用
../sibling_name
。
现在我相信您可以浏览目录了。浏览目录并列出目录中包含的文件和文件夹。
我想这对你有帮助。
const fs = require('fs');
const path = require('path');
function getFile(dirPath) {
const files = fs.readdirSync(dirPath);
files.forEach(function (item) {
const currentPath = path.join(dirPath, item),
isFile = fs.statSync(currentPath).isFile(),
isDir = fs.statSync(currentPath).isDirectory();
if (isFile) {
// console.log(currentPath);
} else if (isDir) {
console.log(currentPath);
getFile(currentPath);
}
});
}
getFile('./'); // this is your server path