ファイルの存在を確認するにはどうすればよいですか?
モジュールのドキュメントにfs
は、メソッドの説明がありfs.exists(path, callback)
ます。しかし、私が理解しているように、ディレクトリのみの存在をチェックします。そして、私はファイルをチェックする必要があります!
これはどのように行うことができますか?
ファイルの存在を確認するにはどうすればよいですか?
モジュールのドキュメントにfs
は、メソッドの説明がありfs.exists(path, callback)
ます。しかし、私が理解しているように、ディレクトリのみの存在をチェックします。そして、私はファイルをチェックする必要があります!
これはどのように行うことができますか?
編集:
ノードv10.0.0
から使用できるfs.promises.access(...)
ファイルが存在するかどうかを確認する非同期コードの例:
function checkFileExists(file) {
return fs.promises.access(file, fs.constants.F_OK)
.then(() => true)
.catch(() => false)
}
stat の代わりに、 new を使用することもできますfs.access(...)
:
チェック用の縮小された短い約束関数:
s => new Promise(r=>fs.access(s, fs.constants.F_OK, e => r(!e)))
使用例:
let checkFileExists = s => new Promise(r=>fs.access(s, fs.constants.F_OK, e => r(!e)))
checkFileExists("Some File Location")
.then(bool => console.log(´file exists: ${bool}´))
拡張された約束の方法:
// returns a promise which resolves true if file exists:
function checkFileExists(filepath){
return new Promise((resolve, reject) => {
fs.access(filepath, fs.constants.F_OK, error => {
resolve(!error);
});
});
}
または、同期的に実行したい場合:
function checkFileExistsSync(filepath){
let flag = true;
try{
fs.accessSync(filepath, fs.constants.F_OK);
}catch(e){
flag = false;
}
return flag;
}
fs.exists(path, callback)
https://nodejs.org/api/fs.html#fs_fs_exists_path_callbackおよびhttps://nodejs.org/api/fs.html#fs_fs_existssync_pathfs.existsSync(path)
を参照してください。
ファイルの存在を同期的にテストするには、ie を使用できます。fs.statSync(path)
. ファイルが存在するfs.Stats
場合はオブジェクトが返されます。 https://nodejs.org/api/fs.html#fs_class_fs_statsを参照してください。それ以外の場合はエラーがスローされ、try / catch ステートメントによってキャッチされます。
var fs = require('fs'),
path = '/path/to/my/file',
stats;
try {
stats = fs.statSync(path);
console.log("File exists.");
}
catch (e) {
console.log("File does not exist.");
}
V6 より前 の古いバージョン: ドキュメントはこちら
const fs = require('fs');
fs.exists('/etc/passwd', (exists) => {
console.log(exists ? 'it\'s there' : 'no passwd!');
});
// or Sync
if (fs.existsSync('/etc/passwd')) {
console.log('it\'s there');
}
アップデート
V6 からの新しいバージョン:ドキュメントfs.stat
fs.stat('/etc/passwd', function(err, stat) {
if(err == null) {
//Exist
} else if(err.code == 'ENOENT') {
// NO exist
}
});
fs.existsSync()
非推奨であることについて多くの不正確なコメントがあります。そうではない。
https://nodejs.org/api/fs.html#fs_fs_existssync_path
fs.exists() は非推奨ですが、 fs.existsSync() は非推奨であることに注意してください。
@フォックス:素晴らしい答えです!これは、いくつかのオプションを備えた少しの拡張機能です。それは私が最近頼りになる解決策として使用しているものです:
var fs = require('fs');
fs.lstat( targetPath, function (err, inodeStatus) {
if (err) {
// file does not exist-
if (err.code === 'ENOENT' ) {
console.log('No file or directory at',targetPath);
return;
}
// miscellaneous error (e.g. permissions)
console.error(err);
return;
}
// Check if this is a file or directory
var isDirectory = inodeStatus.isDirectory();
// Get file size
//
// NOTE: this won't work recursively for directories-- see:
// http://stackoverflow.com/a/7550430/486547
//
var sizeInBytes = inodeStatus.size;
console.log(
(isDirectory ? 'Folder' : 'File'),
'at',targetPath,
'is',sizeInBytes,'bytes.'
);
}
PS まだ使用していない場合は、fs-extra をチェックしてください。かなり便利です。 https://github.com/jprichardson/node-fs-extra )
fs.statSync(path, function(err, stat){
if(err == null) {
console.log('File exists');
//code when all ok
}else if (err.code == "ENOENT") {
//file doesn't exist
console.log('not file');
}
else {
console.log('Some other error: ', err.code);
}
});
https://nodejs.org/api/fs.html#fs_fs_access_path_mode_callbackに見られるように、私はこのようにしました
fs.access('./settings', fs.constants.F_OK | fs.constants.R_OK | fs.constants.W_OK, function(err){
console.log(err ? 'no access or dir doesnt exist' : 'R/W ok');
if(err && err.code === 'ENOENT'){
fs.mkdir('settings');
}
});
これに問題はありますか?
function fileExists(path, cb){
return fs.access(path, fs.constants.F_OK,(er, result)=> cb(!err && result)) //F_OK checks if file is visible, is default does no need to be specified.
}
ドキュメントによると、access()
非推奨の代わりに使用する必要がありますexists()
function fileExists(path, cb){
return new Promise((accept,deny) =>
fs.access(path, fs.constants.F_OK,(er, result)=> cb(!err && result))
);
}
var fs = require('fs-extra')
await fs.pathExists(filepath)
ご覧のとおり、はるかに簡単です。そして、promisify に対する利点は、このパッケージ (完全なインテリセンス/タイプスクリプト) で完全なタイピングができることです! (+-10.000) 他のライブラリが依存しているため、ほとんどの場合、このライブラリは既に含まれています。
昔は座る前にいつも椅子があるかどうかを確認してから座っていました。コーチに座るなどの代替案があります。今 node.js サイトが提案するだけで(チェックする必要はありません)、答えは次のようになります。
fs.readFile( '/foo.txt', function( err, data )
{
if(err)
{
if( err.code === 'ENOENT' )
{
console.log( 'File Doesn\'t Exist' );
return;
}
if( err.code === 'EACCES' )
{
console.log( 'No Permission' );
return;
}
console.log( 'Unknown Error' );
return;
}
console.log( data );
} );
2014 年 3 月のhttp://fredkschott.com/post/2014/03/understanding-error-first-callbacks-in-node-js/から取得したコードを、コンピューターに合わせてわずかに変更しました。許可もチェックします-テストするための許可を削除しますchmod a-r foo.txt
fs.stat
ターゲットがファイルまたはディレクトリであるかどうかを確認するために使用でき、ファイルを書き込み/読み取り/実行できるかどうかを確認するために使用できますfs.access
。path.resolve
(ターゲットのフルパスを取得するために使用することを忘れないでください)
ドキュメンテーション:
完全な例 (TypeScript)
import * as fs from 'fs';
import * as path from 'path';
const targetPath = path.resolve(process.argv[2]);
function statExists(checkPath): Promise<fs.Stats> {
return new Promise((resolve) => {
fs.stat(checkPath, (err, result) => {
if (err) {
return resolve(undefined);
}
return resolve(result);
});
});
}
function checkAccess(checkPath: string, mode: number = fs.constants.F_OK): Promise<boolean> {
return new Promise((resolve) => {
fs.access(checkPath, mode, (err) => {
resolve(!err);
});
});
}
(async function () {
const result = await statExists(targetPath);
const accessResult = await checkAccess(targetPath, fs.constants.F_OK);
const readResult = await checkAccess(targetPath, fs.constants.R_OK);
const writeResult = await checkAccess(targetPath, fs.constants.W_OK);
const executeResult = await checkAccess(targetPath, fs.constants.X_OK);
const allAccessResult = await checkAccess(targetPath, fs.constants.F_OK | fs.constants.R_OK | fs.constants.W_OK | fs.constants.X_OK);
if (result) {
console.group('stat');
console.log('isFile: ', result.isFile());
console.log('isDir: ', result.isDirectory());
console.groupEnd();
}
else {
console.log('file/dir does not exist');
}
console.group('access');
console.log('access:', accessResult);
console.log('read access:', readResult);
console.log('write access:', writeResult);
console.log('execute access:', executeResult);
console.log('all (combined) access:', allAccessResult);
console.groupEnd();
process.exit(0);
}());
非同期バージョン用!そしてお約束バージョンで!ここにきれいで簡単な方法があります!
try {
await fsPromise.stat(filePath);
/**
* File exists!
*/
// do something
} catch (err) {
if (err.code = 'ENOENT') {
/**
* File not found
*/
} else {
// Another error!
}
}
よりよく説明するための私のコードからのより実用的なスニペット:
try {
const filePath = path.join(FILES_DIR, fileName);
await fsPromise.stat(filePath);
/**
* File exists!
*/
const readStream = fs.createReadStream(
filePath,
{
autoClose: true,
start: 0
}
);
return {
success: true,
readStream
};
} catch (err) {
/**
* Mapped file doesn't exists
*/
if (err.code = 'ENOENT') {
return {
err: {
msg: 'Mapped file doesn\'t exists',
code: EErrorCode.MappedFileNotFound
}
};
} else {
return {
err: {
msg: 'Mapped file failed to load! File system error',
code: EErrorCode.MappedFileFileSystemError
}
};
}
}
上記の例はデモンストレーション用です。読み取りストリームのエラー イベントを使用できたはずです。エラーをキャッチするために!そして、2 つの呼び出しをスキップします。