使用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错误,但后来我注意到输出的顺序都不正常。此外,我可以在shell中使用echo (没有sudo -并且我使用sudo node...运行app.js文件)很好地写入文件。
如果真的是这样,你知道为什么所有的东西都异步运行吗?提前感谢
发布于 2020-01-28 10:29:54
Node的fs、writeFile和readFile是异步函数。如果你想要同步函数,你应该使用fs.writeFileSync和fs.readFileSync。
请注意,这意味着您必须删除挂起writeFile和readFile的现有回调函数。
您可以在此处的Node.js文档中了解同步和非同步函数之间的区别:https://nodejs.org/api/fs.html#fs_fs_readfilesync_path_options
https://stackoverflow.com/questions/59941180
复制相似问题