Reputation: 2776
We can give a string arg to fs.readFile to represent a file path
fs.readFile('/etc/passwd', (err, data) => {
if (err) throw err;
console.log(data);
});
But I notice the offical documentation said:
fs.readFile(path[, options], callback)
path
can be a Buffer or an integer. Then I try
const fs = require('fs')
fs.readFile(1, (err, data) => {
if (err) throw err;
console.log(data);
});
Then it throw an error.
I am really confused, how this arg can be a integer? Can anybody gives a example?
Upvotes: 2
Views: 1428
Reputation: 1332
According to the official documentation: path
is either string
or Buffer
or URL
or integer
, and the description of the parameter is: "filename or file descriptor".
string
| Buffer
| URL
- path
is treated as a filename (something like "/path/to/your/file"
)
integer
- path
is treated as a file descriptor.
So if you pass an integer
, NodeJS accesses the file by the file descriptor.
Read more about how NodeJS handles file descriptors.
Upvotes: 1
Reputation: 203514
The integer argument that you can pass should represent a valid file descriptor. For example, stdin
typically has file descriptor 0, so to read a "file" from stdin
you can use this:
fs.readFile(0, (err, data) => {
if (err) throw err;
console.log(data);
});
Instead of 0, you can also use process.stdin.fd
.
Another way to get a file descriptor is to use fs.open()
.
Upvotes: 3