如何将文件写入每个读取的目录?
我有以下文件夹结构,并希望在每个目录中创建一个文件来指示读取了哪些文件。创建文件后,我想使用该文件作为条件来确定是否应该跳过或从该目录中读取。
问题
- 如何将文件写入已读取所有文件的目录?
- 如何在条件逻辑中使用该文件来读取或跳过该文件目录?
当前文件夹结构(运行nodejs之前)
- 子文件夹1 -- 文件 1 -- 文件 2 -- 文件 3 子
- 文件夹 2 -- 文件 3 -- 文件 4
- 子文件夹 3 -- 文件 5 -- 文件 6
所需输出(运行 nodejs 文件后)
- 子文件夹 1 -- 文件 1 -- 文件 2 -- 文件 3 -- files-read.txt
- 子文件夹 2 -- 文件 3 -- 文件 4 -- files-read.txt
- 子文件夹 3 -- 文件 5 -- 文件 6 -- files-read.txt
我尝试过但卡住了
const fs = require('fs');
var targetDirectory = '../my/path/to/target';
var filesRead = [];
fs.readdir(targetDirectory, function (err, files) {
if(err) return console.log('error: ' + err);
files.forEach(function(file) {
// HELP - how do i not read if files-read.txt already exists in directory?
filesRead.push(file);
});
});
var fileName = 'files-read.txt';
fs.writeFile(fileName, filesRead, function (err) {
if(err) return console.log('error: ' + err);
/// help -- how do i only write if files-read.text doesn't exist?
console.log('finished writing');
});
I have the following folder structure below and wanted to create a file in each directory indicating which files were read. After the file is created, I want to use that file as a conditional to determine if I should skip or read from that directory.
Question(s)
- How can I write a file to the directory with all the files read?
- How can I use that file in conditional logic to read or skip that file directory?
Current Folder Structure (before running nodejs)
- sub folder 1
-- file 1
-- file 2
-- file 3 - sub folder 2
-- file 3
-- file 4 - sub folder 3
-- file 5
-- file 6
Desired Output (after running nodejs file)
- sub folder 1
-- file 1
-- file 2
-- file 3
-- files-read.txt - sub folder 2
-- file 3
-- file 4
-- files-read.txt - sub folder 3
-- file 5
-- file 6
-- files-read.txt
What I have tried but got stuck
const fs = require('fs');
var targetDirectory = '../my/path/to/target';
var filesRead = [];
fs.readdir(targetDirectory, function (err, files) {
if(err) return console.log('error: ' + err);
files.forEach(function(file) {
// HELP - how do i not read if files-read.txt already exists in directory?
filesRead.push(file);
});
});
var fileName = 'files-read.txt';
fs.writeFile(fileName, filesRead, function (err) {
if(err) return console.log('error: ' + err);
/// help -- how do i only write if files-read.text doesn't exist?
console.log('finished writing');
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要循环浏览子文件夹。
在你的情况下,它看起来像这样:
You need to cycle through the sub folders.
In your case it would look like this: