Nodejs 'fs' 异步方法 运行

Nodejs 'fs' methods running asynchronously

使用 Node.js 中的 fs 包,我得到了一些意想不到的结果,我希望在这里有所启发。

我有以下代码:

client.on('fileChannel', function(data){
        console.log(data);

        fs.writeFile('/sys/kernel/config/usb_gadget/kvm-gadget/UDC', "", (err) => {
            if (err) {console.log(err)};
            console.log('UDC Halted');
        });

        fs.readFile('/sys/kernel/config/usb_gadget/kvm-gadget/UDC', (err, data) => {
            if (err) {console.log(err)};
            console.log(data.toString('utf8'));
        });


        // Attach file to libcomposite
        if (data.Command === "Attach") {

            numAttachedFiles = Object.keys(fileTracker).length;

            lunNum = 'lun.'+numAttachedFiles;
                fileTracker[lunNum] = data.Argument;
                editFile = '/sys/kernel/config/usb_gadget/kvm-gadget/functions/mass_storage.usb/'+lunNum+'/file';
                fs.writeFile(editFile, __dirname+'/uploads/'+data.Argument, (err) => {
                    if (err) {console.log(err)};
                    console.log('File Attached');
                });
        }

        // Reconnect UDC
        fs.readdir('/sys/class/udc', function(err, dirContents) {
            console.log(dirContents);
                if (err) {console.log(err)};

                fs.writeFile('/sys/kernel/config/usb_gadget/kvm-gadget/UDC', dirContents[0], (err) => {
                    if (err) {console.log(err)};
                    console.log('UDC Reconnected');
                });
        });

    });

这导致(在 // 之后调用输入):

{ Command: 'Attach', Argument: 'jsmpeg-master.zip' } // console.log(data);
[ 'fe980000.usb' ] // console.log(dirContents);
UDC Halted // console.log('UDC Halted');
File Attached // console.log('File Attached');
[Error: EBUSY: resource busy or locked, write] {
  errno: -16,
  code: 'EBUSY',
  syscall: 'write'
} // fs.writeFile('/sys/kernel/config/usb_gadget/kvm-gadget/UDC'...if (err) {console.log(err)};
UDC Reconnected // console.log('UDC Reconnected');
fe980000.usb // console.log(data.toString('utf8'));

起初我以为是权限问题导致了 EBUSY 错误,但后来我注意到输出的顺序完全不正常。此外,我可以使用 echo(没有 sudo - 我 运行 app.js 文件使用 sudo node...)在 shell.

任何想法为什么一切都可能 运行 异步,如果这确实发生了什么?提前致谢

Node的fs writeFile和readFile是异步函数。如果你想要同步函数,你应该使用 fs.writeFileSync 和 fs.readFileSync.

请注意,这意味着您必须删除现有的挂起 writeFile 和 readFile 的回调函数。

您可以在此处的 Node.js 文档中阅读同步和非同步功能之间的区别:https://nodejs.org/api/fs.html#fs_fs_readfilesync_path_options