これを行う方法を説明する検索結果が得られないようです。
私がやりたいのは、特定のパスがファイルなのかディレクトリ(フォルダ)なのかを知ることだけです。
これを行う方法を説明する検索結果が得られないようです。
私がやりたいのは、特定のパスがファイルなのかディレクトリ(フォルダ)なのかを知ることだけです。
以下はあなたに言うべきです。ドキュメントから:
fs.lstatSync(path_string).isDirectory()
fs.stat()およびfs.lstat()から返されるオブジェクトはこのタイプです。
stats.isFile() stats.isDirectory() stats.isBlockDevice() stats.isCharacterDevice() stats.isSymbolicLink() // (only valid with fs.lstat()) stats.isFIFO() stats.isSocket()
上記の解決策はthrow
次のError
ようになります。たとえば、またはは存在しfile
ませdirectory
ん。
true
またはfalse
アプローチが必要な場合はfs.existsSync(dirPath) && fs.lstatSync(dirPath).isDirectory();
、以下のコメントでジョセフが述べたように試してください。
新しいfs.promisesAPIを使用できます
const fs = require('fs').promises;
(async() => {
const stat = await fs.lstat('test.txt');
console.log(stat.isFile());
})().catch(console.error)
パスがファイルであるかディレクトリであるかを非同期で検出する方法は次のとおりです。これは、ノードで推奨されるアプローチです。fs.lstatを使用する
const fs = require("fs");
let path = "/path/to/something";
fs.lstat(path, (err, stats) => {
if(err)
return console.log(err); //Handle error
console.log(`Is file: ${stats.isFile()}`);
console.log(`Is directory: ${stats.isDirectory()}`);
console.log(`Is symbolic link: ${stats.isSymbolicLink()}`);
console.log(`Is FIFO: ${stats.isFIFO()}`);
console.log(`Is socket: ${stats.isSocket()}`);
console.log(`Is character device: ${stats.isCharacterDevice()}`);
console.log(`Is block device: ${stats.isBlockDevice()}`);
});
同期APIを使用する場合の注意:
同期フォームを使用すると、例外がすぐにスローされます。try / catchを使用して、例外を処理したり、例外を発生させたりすることができます。
try{
fs.lstatSync("/some/path").isDirectory()
}catch(e){
// Handle error
if(e.code == 'ENOENT'){
//no such file or directory
//do something
}else {
//do something else
}
}
真剣に、質問は5年間存在し、素敵なファサードはありませんか?
function isDir(path) {
try {
var stat = fs.lstatSync(path);
return stat.isDirectory();
} catch (e) {
// lstatSync throws an error if path doesn't exist
return false;
}
}
path
必要に応じて、おそらくノードのモジュールに依存することができます。
ファイルシステムにアクセスできない場合(たとえば、ファイルがまだ作成されていない場合)、追加の検証が本当に必要でない限り、ファイルシステムにアクセスすることは避けたいと思うでしょう。.<extname>
チェックしているものが次の形式であると想定できる場合は、名前を確認してください。
明らかに、extnameのないファイルを探している場合は、確実にファイルシステムにアクセスする必要があります。ただし、より複雑になるまでは単純にしてください。
const path = require('path');
function isFile(pathItem) {
return !!path.extname(pathItem);
}
これが私が使っている関数です。誰もこの投稿を利用していないpromisify
のでawait/async
、共有したいと思いました。
const promisify = require('util').promisify;
const lstat = promisify(require('fs').lstat);
async function isDirectory (path) {
try {
return (await lstat(path)).isDirectory();
}
catch (e) {
return false;
}
}
注:require('fs').promises;
1年間実験的であるため、使用しません。信頼しない方がよいでしょう。
ノード10.10以降でfs.readdir
は、ファイル名だけでなくwithFileTypes
ディレクトリエントリを返すオプションがありfs.Dirent
ます。ディレクトリエントリには、やname
などの便利なメソッドが含まれているため、明示的に呼び出す必要はありません。isDirectory
isFile
fs.lstat
次のように使用できます。
import { promises as fs } from 'fs';
// ./my-dir has two subdirectories: dir-a, and dir-b
const dirEntries = await fs.readdir('./my-dir', { withFileTypes: true });
// let's filter all directories in ./my-dir
const onlyDirs = dirEntries.filter(de => de.isDirectory()).map(de => de.name);
// onlyDirs is now [ 'dir-a', 'dir-b' ]
1)それが私がこの質問を見つけた方法だからです。
上記の回答は、ファイルシステムにファイルまたはディレクトリであるパスが含まれているかどうかを確認します。ただし、特定のパスだけがファイルなのかディレクトリなのかは識別されません。
答えは、「/」を使用してディレクトリベースのパスを識別することです。->「/c/ dos /run/」のように。<-トレーリング期間。
まだ書き込まれていないディレクトリまたはファイルのパスのように。または、別のコンピューターからのパス。または、同じ名前のファイルとディレクトリの両方が存在するパス。
// /tmp/
// |- dozen.path
// |- dozen.path/.
// |- eggs.txt
//
// "/tmp/dozen.path" !== "/tmp/dozen.path/"
//
// Very few fs allow this. But still. Don't trust the filesystem alone!
// Converts the non-standard "path-ends-in-slash" to the standard "path-is-identified-by current "." or previous ".." directory symbol.
function tryGetPath(pathItem) {
const isPosix = pathItem.includes("/");
if ((isPosix && pathItem.endsWith("/")) ||
(!isPosix && pathItem.endsWith("\\"))) {
pathItem = pathItem + ".";
}
return pathItem;
}
// If a path ends with a current directory identifier, it is a path! /c/dos/run/. and c:\dos\run\.
function isDirectory(pathItem) {
const isPosix = pathItem.includes("/");
if (pathItem === "." || pathItem ==- "..") {
pathItem = (isPosix ? "./" : ".\\") + pathItem;
}
return (isPosix ? pathItem.endsWith("/.") || pathItem.endsWith("/..") : pathItem.endsWith("\\.") || pathItem.endsWith("\\.."));
}
// If a path is not a directory, and it isn't empty, it must be a file
function isFile(pathItem) {
if (pathItem === "") {
return false;
}
return !isDirectory(pathItem);
}
ノードバージョン:v11.10.0-2019年2月
最後の考え:なぜファイルシステムにヒットするのですか?