Welcome to Code Forum!

Join a community that supports you and your coding journey from day one. We strive to be a friendly, supportive community that empowers everyone to be better developers. By registering with us, you'll be able to discuss, share and private message with other members of our community.

SignUp Now!
  • Guest, before posting your code please take these rules into consideration:
    • It is required to use our BBCode feature to display your code. While within the editor click < / > or >_ and place your code within the BB Code prompt. This helps others with finding a solution by making it easier to read and easier to copy.
    • You can also use markdown to share your code. When using markdown your code will be automatically converted to BBCode. For help with markdown check out the markdown guide.
    • Don't share a wall of code. All we want is the problem area, the code related to your issue.

    GIF shows where to locate </> in the thread and or post editor toolbar.
    To learn more about how to use our BBCode feature, review our "How to post your code into threads" here.

    Thank you, Code Forum.

(Nodejs) Trying to read a file but not getting the output I expect

noweare

Active Coder
I am learning nodejs and I am just getting my feet wet with it.
For practice I am trying to read 2048 bytes from a file then put it in a buffer
and repeating until I have read the whole file.

In the code I print out 'hello' in the readmyFile function. I do see that repeatedly
but I do not see bytesRead or the contents of the buffer. I guess I need to learn
how to debug my code properly.

Thanks to anyone to help shed some light on this. JavaScript is challenging !
Btw : the file is Int8 which represent audio.

Code:
// read from file into buffer until contents have been read, then close file
const path = require('path');
const fsPromises = require('fs').promises;
const fs = require('fs');

let mypath = path.join(__dirname, 'files', 'myvoice.raw');
let fd = 0;
let interval = 0;
let count = 0;

const buffer = Buffer.alloc(2048); // Create a buffer to store the data

function closeFile() {
   fs.close(fd, (err) => {
        if (err) {
            console.error('Error closing file:', err);
        }
        else {
            clearInterval(interval);
            console.log('bytes read = 0, file closed');
            
        }
    })
}

//Open the file for reading
function openFile() {
    fs.open(mypath, 'r', (err, fd) => {
        if (err) {
            console.error('Error opening file:', err);
            return false; 
        }
        else {
            console.log(`fd : ${fd}`);
            //console.log(typeof(fd));
            //readmyFile();
            // return fd;
            //   interval = setInterval(readmyFile, 1000);
        }
  })
}


function readmyFile() {
    // Read 2048 bytes from the file each iteration
    console.log('hello');
    
    fs.read(fd, buffer, 0, 2048, -1, (err, bytesRead, buffer) => {
    if (err) {
        console.error('Error reading file:', err);
        return;
    }
    else {
        console.log('bytes read : ', bytesRead);
        console.log(buffer);
         if (bytesRead == 0){
                closeFile();
        }
    }
    })
}

// function begin(){
    
// }

 console.log('starting program');

 openFile();
 //setTimeout(begin, 2000);  //making sure  the file is opened before calling readmyFile
 interval = setInterval(readmyFile, 2000);
 
Solution
I am learning nodejs and I am just getting my feet wet with it.
For practice I am trying to read 2048 bytes from a file then put it in a buffer
and repeating until I have read the whole file.

In the code I print out 'hello' in the readmyFile function. I do see that repeatedly
but I do not see bytesRead or the contents of the buffer. I guess I need to learn
how to debug my code properly.

Thanks to anyone to help shed some light on this. JavaScript is challenging !
Btw : the file is Int8 which represent audio.

Code:
// read from file into buffer until contents have been read, then close file
const path = require('path');
const fsPromises = require('fs').promises;
const fs = require('fs');

let mypath = path.join(__dirname, 'files'...
I am learning nodejs and I am just getting my feet wet with it.
For practice I am trying to read 2048 bytes from a file then put it in a buffer
and repeating until I have read the whole file.

In the code I print out 'hello' in the readmyFile function. I do see that repeatedly
but I do not see bytesRead or the contents of the buffer. I guess I need to learn
how to debug my code properly.

Thanks to anyone to help shed some light on this. JavaScript is challenging !
Btw : the file is Int8 which represent audio.

Code:
// read from file into buffer until contents have been read, then close file
const path = require('path');
const fsPromises = require('fs').promises;
const fs = require('fs');

let mypath = path.join(__dirname, 'files', 'myvoice.raw');
let fd = 0;
let interval = 0;
let count = 0;

const buffer = Buffer.alloc(2048); // Create a buffer to store the data

function closeFile() {
   fs.close(fd, (err) => {
        if (err) {
            console.error('Error closing file:', err);
        }
        else {
            clearInterval(interval);
            console.log('bytes read = 0, file closed');
           
        }
    })
}

//Open the file for reading
function openFile() {
    fs.open(mypath, 'r', (err, fd) => {
        if (err) {
            console.error('Error opening file:', err);
            return false;
        }
        else {
            console.log(`fd : ${fd}`);
            //console.log(typeof(fd));
            //readmyFile();
            // return fd;
            //   interval = setInterval(readmyFile, 1000);
        }
  })
}


function readmyFile() {
    // Read 2048 bytes from the file each iteration
    console.log('hello');
   
    fs.read(fd, buffer, 0, 2048, -1, (err, bytesRead, buffer) => {
    if (err) {
        console.error('Error reading file:', err);
        return;
    }
    else {
        console.log('bytes read : ', bytesRead);
        console.log(buffer);
         if (bytesRead == 0){
                closeFile();
        }
    }
    })
}

// function begin(){
   
// }

 console.log('starting program');

 openFile();
 //setTimeout(begin, 2000);  //making sure  the file is opened before calling readmyFile
 interval = setInterval(readmyFile, 2000);
You should try this: Update fd inside the callback and only start the interval once the file is successfully opened.


JavaScript:
const path = require('path');
const fs = require('fs');

let mypath = path.join(__dirname, 'files', 'myvoice.raw');
let fd = null;
let interval = null;

const buffer = Buffer.alloc(2048); // Allocate 2048-byte buffer

function closeFile() {
    fs.close(fd, (err) => {
        if (err) {
            console.error('Error closing file:', err);
        } else {
            clearInterval(interval);
            console.log('bytes read = 0, file closed');
        }
    });
}

function readmyFile() {
    console.log('hello');

    fs.read(fd, buffer, 0, 2048, null, (err, bytesRead) => {
        if (err) {
            console.error('Error reading file:', err);
            return;
        }

        console.log('bytes read :', bytesRead);

        if (bytesRead === 0) {
            closeFile();
        } else {
            // Show a slice of buffer for readability
            console.log(buffer.slice(0, bytesRead));
        }
    });
}

function openFile() {
    fs.open(mypath, 'r', (err, fileDescriptor) => {
        if (err) {
            console.error('Error opening file:', err);
            return;
        }

        fd = fileDescriptor;
        console.log(`File opened, fd: ${fd}`);
        interval = setInterval(readmyFile, 500); // start reading after opening
    });
}

console.log('Starting program...');
openFile();
 
Solution
Yes, your suggestions worked. Thank you sir. Coming from a C background JS is so different. Getting my head around the asynchronous nature of JS makes it a lot different than C.

As it has been a couple of days since I posted this question, I read up on promises and async / await and used the promise version of the functions to get rid of using the interval timer.

Thank you for your help !
 
Last edited:
Back
Top Bottom