如何检查路径中的每个文件是否可供读取

时间:2018-06-14 14:22:44

标签: javascript node.js fs readdir

我正在尝试阅读特定路径的内容。为此,我使用了以下代码:

CODE1

const contentsOfPersonalFolder = fs.readdirSync(rootPathToPersonal);

但我提前知道我没有访问权限来读取将从上一行代码返回的一些内容。 要检查我是否具有读取某些文件的访问权限,我将使用以下代码

码2

try {
  fs.accessSync(path, fs.constants.R_OK);
  logger.info('The directory: ', path, 'can be read');
} catch (err) {
  logger.error('The directory: ', path, 'can not be read due inaccessibility');
}

现在的问题是,code1中的代码将返回指定路径中所有可用文件的数组。如果其中一个文件不是 可读的权利保护,然后它将抛出,程序将抛出。

我想要实现的是遍历code1中指定路径中的所有可用文件,然后使用code2中的代码检查每个项目 如果文件可以读取,我想做一些逻辑,如果无法阅读,我会做其他事情。

请告诉我如何实现这一目标。

2 个答案:

答案 0 :(得分:1)

您可以使用fs.access检查用户权限 https://nodejs.org/api/fs.html#fs_fs_access_path_mode_callback

const testFolder = './tests/';
const fs = require('fs');

fs.readdir(testFolder, (err, files) => {
  files.forEach(file => {
    console.log(file);
    fs.access(file, fs.constants.R_OK, (err) => {
        if (err) { 
            console.error("file is not readable");
            return;
        }

        // do your reading operations
    });
  });
})

答案 1 :(得分:0)

public class ListenOrder extends Service implements ChildEventListener {

    private static final int MY_NOTIFICATION_ID = 12345;
    private static final int MY_REQUEST_CODE = 100;
    FirebaseDatabase db;
    DatabaseReference requests;
    private NotificationCompat.Builder notBuilder;

    public ListenOrder() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public void onCreate() {
        super.onCreate();
        this.notBuilder = new NotificationCompat.Builder(this);
        this.notBuilder.setAutoCancel(true);
        db = FirebaseDatabase.getInstance();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        requests = db.getReference("Requests").child(Common.currentUser.getPhone());
        requests.addChildEventListener(this);
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onChildAdded(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {

    }

    @Override
    public void onChildChanged(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {
        //Trigger here:
        Request request = dataSnapshot.getValue(Request.class);
        Toast.makeText(this, request.getKey() + "", Toast.LENGTH_SHORT).show();
        showNotification(dataSnapshot.getKey(), request);
    }

    public void showNotification(String key, Request request) {
        this.notBuilder.setSmallIcon(R.mipmap.ic_launcher);
        this.notBuilder.setTicker("TheFoodHouse");
        this.notBuilder.setWhen(System.currentTimeMillis() + 10 * 1000);
        this.notBuilder.setContentTitle("Your order was updated");
        this.notBuilder.setContentText("Order #" + key + " was updated status to " + Common.convertCodeToStatus(String.valueOf(request.getStatus())));
        Intent intent = new Intent(this, OrderStatusActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, MY_REQUEST_CODE,
                intent, PendingIntent.FLAG_UPDATE_CURRENT);
        this.notBuilder.setContentIntent(pendingIntent);
        NotificationManager notificationService =
                (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
        Notification notification = notBuilder.build();
        notificationService.notify(MY_NOTIFICATION_ID, notification);
    }

    @Override
    public void onChildRemoved(@NonNull DataSnapshot dataSnapshot) {

    }

    @Override
    public void onChildMoved(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {

    }

    @Override
    public void onCancelled(@NonNull DatabaseError databaseError) {

    }
}