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.
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);