Search code examples
javascriptnode.jsfsexceljs

Getting bad file descriptor error while using fs.openFileSync in node.js


I am putting the data from xlsx file into csv file. This is my code:-

const file = fs.openSync('/home/rahul/example/sample.csv', 'w')
const workbook = new exceljs.Workbook();
workbook.xlsx.readFile( path.join(__dirname, '' + args.filename)).then(function() {

    const worksheet = workbook.getWorksheet('sheet3');

    worksheet.eachRow(function(row){
        try{
            const buffer = array2CsvLine(row.values)
            fs.writeSync(file, buffer, { flag: 'a' })
        }
        catch(err){
            console.log('error related to fs.writeSync function')
            console.log(err)
        }
    })
    //fs.closeSync(file)
})
fs.closeSync(file)

it is giving me this error:-

error related to fs.writeSync function
{ Error: EBADF: bad file descriptor, write
    at Object.writeSync (fs.js:569:3)
    at /home/rahul/min-wage/xls2csv.js:73:16
    at _rows.forEach.row (/home/rahul/min-wage/node_modules/exceljs/lib/doc/worksheet.js:515:11)
    at Array.forEach (<anonymous>)
    at Worksheet.eachRow (/home/rahul/min-wage/node_modules/exceljs/lib/doc/worksheet.js:513:18)
    at /home/rahul/min-wage/xls2csv.js:70:15 errno: -9, syscall: 'write', code: 'EBADF' }

But if I use the commented fs.closeSync(file), then it works fine. I don't know why is this happening? I think, I can close file at global place too.


Solution

  • The call to:

    fs.closeSync(file)
    

    ...is called before the promise resolves. Just remove it from the last line and uncomment the other call inside the promise.