如何在nodejs的目录中获取带有.txt扩展名的第一个文件? [英] How to get the first file with a .txt extension in a directory with nodejs?

查看:45
本文介绍了如何在nodejs的目录中获取带有.txt扩展名的第一个文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我所有文件所在的目录是:'/ usr / home / jordan',我下面有很多文件(在目录本身,但是一个以.txt扩展名命名的文件。

The directory all my files are in is: '/usr/home/jordan' and I have many files under there (in the directory itself, but one file that is named with a .txt extension.

使用nodejs和fs,我想把第一个带有txt扩展名的文件(或任何文件)放到mytxtfilepath中。我在整个目录中只有一个.txt文件。许多其他文件,但具有不同的扩展名)单个.txt文件可以命名为ANYTHING,我无法保证在任何给定时间名称将是什么,只有它以.txt结尾:

With nodejs and fs, I want to put that first file (or any file) with a txt extension into "mytxtfilepath". I only have a single .txt file in the whole directory (amongst many other files but with different extensions) The single .txt file could be named ANYTHING, I cannot guarantee what the name will be at any given time, only that it ends in .txt:

var homedir = "/usr/home/jordan";
var mytxtfilepath=homedir + "???????";
fs.readfile(mytxtfilepath, function(err,data) {
  console.log(data);
});

如何在没有硬编码txt文件名的情况下将正确的路径放到txt文件中?

How do I put the correct path to my txt file without hardcoding the name of the txt file itself?

推荐答案

var files = fs.readdirSync(homedir);
var path = require('path');

for(var i in files) {
   if(path.extname(files[i]) === ".txt") {
       //do something
   }
}

这篇关于如何在nodejs的目录中获取带有.txt扩展名的第一个文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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