Skip to main content

fs

fs.readdir()

fs.readdir( path, options, callback )

Parameters: This method accept three parameters as mentioned above and described below:

  • path: It holds the path of the directory from where the contents have to be read. It can be a String, Buffer or URL.

  • options:

    It is an object that can be used to specify optional parameters that will affect the method. It has two optional parameters:

    • encoding: It is a string value which specifies which encoding would be used for the filenames given to the callback argument. The default value is ‘utf8’.
    • withFileTypes: It is a boolean value which specifies whether the files would be returned as fs.Dirent objects. The default value is ‘false’.
  • callback:

    It is the function that would be called when the method is executed.

    • err: It is an error that would be thrown if the operation fails.
    • files: It is an array of String, Buffer or fs.Dirent objects that contain the files in the directory.

Below examples illustrate the fs.readdir() method in Node.js:

Example 1: This example uses fs.readdir() method to return the file names or file objects in the directory.

// Node.js program to demonstrate the
// fs.readdir() method

// Import the filesystem module
const fs = require('fs');

// Function to get current filenames
// in directory
fs.readdir(__dirname, (err, files) => {
if (err)
console.log(err);
else {
console.log("\nCurrent directory filenames:");
files.forEach(file => {
console.log(file);
})
}
})

// Function to get current filenames
// in directory with "withFileTypes"
// set to "true"

fs.readdir(__dirname,
{ withFileTypes: true },
(err, files) => {
console.log("\nCurrent directory files:");
if (err)
console.log(err);
else {
files.forEach(file => {
console.log(file);
})
}
})

fs.stat() Method

讀取資料,但是是非同步的方式,可用在外步讀資源的時候,不用一直等待 The fs.stat() method is used to return information about the given file or directory. It returns an fs.Stat object which has several properties and methods to get details about the file or directory.

fs.stat( path, options, callback )

Parameters: This method accept three parameters as mentioned above and described below:

  • path: It holds the path of the file or directory that has to be checked. It can be a String, Buffer or URL.

  • options:

    It is an object that can be used to specify optional parameters that will affect the output. It has one optional parameter:

    • bigint: It is a boolean value which specifies if the numeric values returned in the fs.Stats object are bigint. The default value is false.
  • callback:

    It is the function that would be called when the method is executed.

    • err: It is an error that would be thrown if the method
    • stats: It is the Stats object that contains the details of the file path.

Below examples illustrate the fs.stat() method in Node.js:

Example 1: This example uses fs.stat() method to get the details of the path.

// Node.js program to demonstrate the
// fs.stat() method

// Import the filesystem module
const fs = require('fs');

// Getting information for a file
fs.stat("example_file.txt", (error, stats) => {
if (error) {
console.log(error);
}
else {
console.log("Stats object for: example_file.txt");
console.log(stats);

// Using methods of the Stats object
console.log("Path is file:", stats.isFile());
console.log("Path is directory:", stats.isDirectory());
}
});

// Getting information for a directory
fs.stat("example_directory.txt", (error, stats) => {
if (error) {
console.log(error);
}
else {
console.log("Stats object for: example_directory.txt");
console.log(stats);

// Using methods of the Stats object
console.log("Path is file:", stats.isFile());
console.log("Path is directory:", stats.isDirectory());
}
});

fs.readFileSync() Method

The fs.readFileSync() method is an inbuilt application programming interface of the fs module which is used to read the file and return its content.

In fs.readFile() method, we can read a file in a non-blocking asynchronous way, but in the fs.readFileSync() method, we can read files in a synchronous way, i.e. we are telling node.js to block other parallel processes and do the current file reading process. That is, when the fs.readFileSync() method is called the original node program stops executing, and the node waits for the fs.readFileSync() function to get executed, after getting the result of the method the remaining node program is executed.

fs.readFileSync( path, options )

Parameters:

  • path: It takes the relative path of the text file. The path can be of URL type. The file can also be a file descriptor. If both the files are in the same folder just give the filename in quotes.
  • options: It is an optional parameter that contains the encoding and flag, the encoding contains data specification. Its default value is null which returns the raw buffer and the flag contains an indication of operations in the file. Its default value is ‘r’.
// Node.js program to demonstrate the
// fs.readFileSync() method

// Include fs module
const fs = require('fs');

// Calling the readFileSync() method
// to read 'input.txt' file
const data = fs.readFileSync('./input.txt',
{ encoding: 'utf8', flag: 'r' });

// Display the file data
console.log(data);

fs.statSync() Method

讀取檔案資料基本檔案 The fs.statSync() method is used to synchronously return information about the given file path. The fs.Stat object returned has several fields and methods to get more details about the file.

Syntax: 

fs.statSync( path, options )

Parameters: This method accept two parameters as mentioned above and described below: 

  • path: It holds the path of the file that has to be checked. It can be a String, Buffer or URL.
  • options: It is an object that can be used to specify optional parameters that will affect the output. It has one optional parameter:
    • bigint: It is a boolean value which specifies if the numeric values returned in the fs.Stats object are bigint. The default value is false.

Returns: It returns a Stats object which contains the details of the file path.
Below examples illustrate the fs.statSync() method in Node.js:
Example 1: This example uses fs.statSync() method to get the details of the path.

const fs = require('fs')
console.log(fs.statSync('./input.txt'))
// output
Stats {
dev: 16777394,
mode: 33188,
nlink: 1,
uid: 1000,
gid: 1000,
rdev: 0,
blksize: 4096,
ino: 508,
size: 9,
blocks: 8,
atimeMs: 1691553416062.0767,
mtimeMs: 1691553416062.0767,
ctimeMs: 1691553416062.0767,
birthtimeMs: 1691553416062.0767,
atime: 2023-08-09T03:56:56.062Z,
mtime: 2023-08-09T03:56:56.062Z,
ctime: 2023-08-09T03:56:56.062Z,
birthtime: 2023-08-09T03:56:56.062Z
}

fs.writeFile() Method

寫出一個新的檔案

The fs.writeFile() method is used to asynchronously write the specified data to a file. By default, the file would be replaced if it exists. The ‘options’ parameter can be used to modify the functionality of the method.

Syntax:

fs.writeFile( file, data, options, callback )

Parameters: This method accept four parameters as mentioned above and described below:

  • file: It is a string, Buffer, URL or file description integer that denotes the path of the file where it has to be written. Using a file descriptor will make it behave similar to fs.write() method.

  • data: It is a string, Buffer, TypedArray or DataView that will be written to the file.

  • options:

    It is an string or object that can be used to specify optional parameters that will affect the output. It has three optional parameter:

    • encoding: It is a string value that specifies the encoding of the file. The default value is ‘utf8’.
    • mode: It is an integer value that specifies the file mode. The default value is 0o666.
    • flag: It is a string value that specifies the flag used while writing to the file. The default value is ‘w’.
  • callback:

    It is the function that would be called when the method is executed.

    • err: It is an error that would be thrown if the operation fails.
// Node.js program to demonstrate the
// fs.writeFile() method

// Import the filesystem module
const fs = require('fs');

let data = "This is a file containing a collection of books.";

fs.writeFile("books.txt", data, (err) => {
if (err)
console.log(err);
else {
console.log("File written successfully\n");
console.log("The written has the following contents:");
console.log(fs.readFileSync("books.txt", "utf8"));
}
});