如果使用openSync打开文件,如何获取node.js中的文件描述符 [英] How to get file descriptor in node.js if you open file using openSync

查看:640
本文介绍了如果使用openSync打开文件,如何获取node.js中的文件描述符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经注意到openSync有一个很大的问题,那就是当你用openSync打开一个文件时,你不会得到文件描述符。如果使用异步调用打开,则只会将其作为回调的参数。问题是你必须有文件描述符来关闭文件!还有其他的东西,程序员可能想要做一个文件,你也需要文件描述符。

这似乎是一个重大的遗漏在FS API node.js不提供访问fd变量的方法,如果使用同步调用打开异步模式,则以异步模式打开回调。这实际上使同步开放不适用于大多数应用程序。

我真的不想在我的开发中使用异步文件打开和关闭,如果我可以避免它,有什么办法获得fd变量我需要在使用同步打开时成功关闭文件吗?解决方案

>除了文件描述符之外,还会从openFileSync中获得什么?

  var fs = require('fs')
var path = require('path')
var fd = fs.openSync(path.join(process.cwd(),'log.txt'),'a')
fs.writeSync(fd ,'contents to append')
setTimeout(function(){
console.log('立即关闭文件')
fs.closeSync(fd)
},10000)

运行 lsof /path/to/log.txt上面的节点脚本正在运行并且在脚本完成之后再次运行 lsof /path/to/log.txt 表明文件正在关闭编辑正确



那就是说你打算通过打开文件来完成什么?也许有一个更好的方法,例如为您的具体情况流媒体

I have noticed what could be a big problem though for openSync, that when you open a file with openSync, you don't get the file descriptor. You only get it as an argument to the callback if you open with the asynchronous call. The problem is that you HAVE to have the file descriptor to close the file! There are other things which a programmer might want to do to a file that you need the file descriptor for as well.

It would seem a significant omission in the fs API for node.js not to provide a way to get access to the fd variable that the call back returns when opening in asynchronous mode if you open using synchronous calls. That would essentially make the synchronous open unuseable for most applications.

I really don't want to have to use the async file opens and closes later on in my development if I can avoid it, is there any way to get the fd variable I need to close the file successfully when using the synchronous open?

解决方案

What else would you get from openFileSync besides a file descriptor?

var fs = require('fs')
var path = require('path')
var fd = fs.openSync(path.join(process.cwd(), 'log.txt'), 'a')
fs.writeSync(fd, 'contents to append')
setTimeout(function () {
  console.log('closing file now')
  fs.closeSync(fd)
}, 10000)

Running lsof /path/to/log.txt while the node script above is running and running lsof /path/to/log.txt again after the script is done shows that the file is being closed correctly

That said what are you trying to accomplish by opening the file? Perhaps there is a better way such as streaming for your specific situation

这篇关于如果使用openSync打开文件,如何获取node.js中的文件描述符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆