如何在不删除Node.js中的目录的情况下从目录中删除所有文件 [英] How to remove all files from directory without removing directory in Node.js

查看:151
本文介绍了如何在不删除Node.js中的目录的情况下从目录中删除所有文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在不使用Node.js删除目录的情况下从目录中删除所有文件?

我想删除临时文件。我对文件系统没有任何好处。

How to remove all files from a directory without removing a directory itself using Node.js?
I want to remove temporary files. I am not any good with filesystems yet.

我找到了这个方法,它将删除文件和目录。在那里,像 / path / to / directory / * 之类的东西将无效。

I have found this method, which will remove files and the directory. In that, something like /path/to/directory/* won't work.

我不知道真的知道应该使用什么命令。感谢您的帮助。

I don't really know what commands should use. Thanks for the help.

推荐答案

要从目录中删除所有文件,首先需要使用<列出目录中的所有文件code> fs.readdir ,然后您可以使用 fs.unlink 删除每个文件。此外 fs.readdir 将仅提供文件名,您需要与目录名称连接以获取完整路径。

To remove all files from a directory, first you need to list all files in the directory using fs.readdir, then you can use fs.unlink to remove each file. Also fs.readdir will give just the file names, you need to concat with the directory name to get the full path.

以下是一个例子

const fs = require('fs');
const path = require('path');

const directory = 'test';

fs.readdir(directory, (err, files) => {
  if (err) throw err;

  for (const file of files) {
    fs.unlink(path.join(directory, file), err => {
      if (err) throw err;
    });
  }
});

这篇关于如何在不删除Node.js中的目录的情况下从目录中删除所有文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆