I am new to node.js. I am trying to read a file in an async
function. In the function I instantiate a class from a module I have created. The constructor of that module calls a method tries to open and read an ASCII text file that is local to the module. The problem is that when I try to do the read, Node just seems to skip over it. No exceptions are thrown that I can see. I am running this in a PyCharm debug session and can set breakpoints that are never triggered.
I have an absolute path to an existing file. I have tried using fs.readFile()
and fs.createReadStream()
with the same result.
The readFile
code I tried came from the Node docs here
fs.readFile(
pathToFile, 'ascii', function (err, data) {
if (err) {
return console.log(err)
}
this.#file_contents = data
}
);
The createReadStream
docs suggested something like:
const readableStream = fs.createReadStream(filePath);
readableStream.on('error', function (error) {
throw error
})
readableStream.on('data', (chunk) => {
this.#file_contents = chunk
})
Does Node need some configuration switch set to allow filesystem reads?
Edit
Thanks all, just what I needed!
CodePudding user response:
No configuration is needed. The read is just non-blocking and asynchronous. That means calling fs.readFile()
just initiates the reading and immediately returns and continues to execute the rest of your code.
Sometime later, it will call your callback with the file data. This is how asynchronous operations work in nodejs. There are synchronous operations if you want like fs.readFileSync()
- though they shouldn't be used in a server except in startup code because they block the event loop and wreck the scalability of your server.
In fact, if you just do this in your file:
const fs = require('fs');
const pathToFile = "./index.txt";
console.log("1");
fs.readFile(pathToFile, 'utf8', data => {
console.log("2");
});
console.log("3");
You will see in your console:
1
3
2
This shows how fs.readFile()
is asynchronous and non-blocking. It will initiate its operation and then immediately return, letting more of your code execute before it completes and then eventually calls its callback.
If this was a single user script or if this was server initialization code, you could just do this:
const fs = require('fs');
const pathToFile = "./index.txt";
console.log("1");
const data = fs.readFileSync(pathToFile, 'utf8');
console.log("2");
You will see in your console:
1
2
CodePudding user response:
No special configuration is needed but i would recommend using fs.readFileSync()
instead of fs.readFile()
Here is an example using an async function
main.js
const fs = require('fs');
(async () => {
let file = await fs.readFileSync("index.txt", {encoding: "ascii"});
console.log(file);
})()
index.txt
hello
and if u want to test it out check here https://replit.com/@MatthewChan18/BlandTallCosmos#index.js