Node.js Error: “Error: EBUSY: resource busy or locked, stat“

abnormal

Error: EBUSY: resource busy or locked, stat 'C:\swapfile.sys'
    at Object.statSync (node:fs:1536:3)
    at D:\NodeJs\node-demo\demo\world.js:7:24
    at FSReqCallback.oncomplete (node:fs:188:23) {
  errno: -4082,
  syscall: 'stat',
  code: 'EBUSY',
  path: 'C:\\swapfile.sys'
}

Node.js v17.1.0

error code

var fs = require('fs');

var rootPath = 'C:\\';
fs.readdir(rootPath, function (err, files) {
    for (var i = 0; i < files.length; i++) {
        var p = rootPath + files[i];
        var stats = fs.statSync(p);
        console.log(rootPath + 'Is it a directory:' + stats.isDirectory())
    }
});

Reason

Prompt error: EBUSY: resource busy or locked, stat indicates that the resource file is busy or locked, that is, the C:\swapfile.Sys file. But there is no such file in the C disk directory, even in the hidden file. But it can be found by opening everything software
is a system file.

Solution:

I don’t know how to solve it. The online solution seems to be invalid, so I can only block the file.

Correct code

var fs = require('fs');

var rootPath = 'C:\\';
fs.readdir(rootPath, function (err, files) {
    for (var i = 0; i < files.length; i++) {
        var p = rootPath + files[i];
        // Skip when encountering swapfile.sys file or System Volume Information directory
        if (p.endsWith('swapfile.sys') || p.endsWith('System Volume Information')) {
            continue;
        }
        var stats = fs.statSync(p);
        console.log(rootPath + 'Is it a directory:' + stats.isDirectory())
    }
});

Read More: