如果您可以成功构建模块附加组件fs-ext,它将在 Windows 上运行。我必须在我的系统上安装 Python 并将其放入路径中,然后才能成功安装和构建。一旦我这样做了,我就能够运行这个测试,它验证了一个子进程不允许读取或写入我有一个羊群的文件:
// open-exclusive.js
const fs = require('fs');
const fsp = fs.promises;
const child = require('child_process');
const { promisify } = require('util');
const execP = promisify(child.exec);
const flock = promisify(require('fs-ext').flock);
const exclusive = fs.constants.S_IRUSR | fs.constants.S_IWUSR | fs.constants.S_IXUSR;
async function run() {
const fHandle = await fsp.open("./temp.txt", "r+", exclusive);
await flock(fHandle.fd, 'ex');
await fHandle.write("Goodbye", 0);
console.log('parent finished write');
const { stdout, stderr } = await execP("node open-exclusive-child.js");
console.log('stdout:', stdout);
console.error('stderr:', stderr);
console.log('parent done exec');
await fHandle.close();
return "good";
}
run().then(result => {
console.log(result);
}).catch(err => {
console.log(err);
});
子进程文件open-exclusive-child.js
const fs = require('fs');
const fsp = fs.promises;
async function run() {
const fHandle = await fsp.open("./temp.txt", "r");
let buf = Buffer.alloc(10);
await fHandle.read(buf, 0, 10, 0);
await fHandle.write("Hello", 0);
console.log('child: finished write');
await fHandle.close();
return "child good"
}
run().then(result => {
console.log(result);
}).catch(err => {
console.log(err);
});
当我运行node open-exclusive.js 时,父进程会打开它,flock 成功,然后子进程将无法读取或写入文件。孩子显然可以“打开”文件,但在尝试读取或写入文件时出现 EBUSY 错误。
事实上,flock 也是同样的过程:
const fs = require('fs');
const fsp = fs.promises;
const { promisify } = require('util');
const execP = promisify(child.exec);
const flock = promisify(require('fs-ext').flock);
const exclusive = fs.constants.S_IRUSR | fs.constants.S_IWUSR | fs.constants.S_IXUSR;
async function run() {
const fHandle = await fsp.open("./temp.txt", "r+", exclusive);
await flock(fHandle.fd, 'ex');
await fHandle.write("Goodbye", 0);
console.log('parent finished write');
const fHandle2 = await fsp.open("./temp.txt", "r");
const buf = Buffer.alloc(10);
console.log("About to read from fHandle2");
let bytes = await fHandle2.read(buf, 0, 10, 0);
console.log(bytes);
await fHandle2.close();
await fHandle.close();
return "good";
}
run().then(result => {
console.log(result);
}).catch(err => {
console.log(err);
});
当我运行它时,我会在控制台中得到它:
node open-exclusive.js
parent finished write
About to read from fHandle2
[Error: EBUSY: resource busy or locked, read] {
errno: -4082,
code: 'EBUSY',
syscall: 'read'
}