首页 > 解决方案 > NodeJs fs.close() TypeError: fd must be a file descriptor

问题描述

我使用 nodejs 在文件上写入。

fs.open(path.join(reportPath), 'a', 666, ( e, fd ) => {
   fs.write( fd, `There is a company named ${companyName}` + os.EOL, null, 'utf8', () => {
      fs.close( (err) => {
        if(err) throw err;
        console.log('write successfull')
     })
   })
 })

它返回一个错误,实际上文件已写入,但该错误使我的服务器停止。因为throw err

这里的错误信息:

TypeError: fd must be a file descriptor
    at Object.fs.close (fs.js:608:11)
    at C:\DATA\source\code\build\modules\desc\controller.js:199:42
    at FSReqWrap.wrapper [as oncomplete] (fs.js:685:5)

标签: node.js

解决方案


我忘记在 fs.close() 上传递文件描述符

fs.open(path.join(reportPath), 'a', 666, ( e, fd ) => {
   fs.write( fd, `There is a company named ${companyName}` + os.EOL, null, 'utf8', () => {
      fs.close(fd, (err) => {
        if(err) throw err;
        console.log('write successfull')
     })
   })
 })

推荐阅读