File System in Next.js
Read File
Read File
1import { promises as fs } from 'fs';
2import path from 'path';
3
4/** ... **/
5
6const getFiles = async (dir, filelist = []) => {
7 const files = await fs.readdir(dir);
8
9 for (const file of files) {
10 const filepath = path.join(dir, file);
11 const stat = await fs.stat(filepath);
12
13 if (stat.isDirectory()) {
14 filelist = await getFiles(filepath, filelist);
15 } else {
16 filelist.push(filepath);
17 }
18 }
19
20 return filelist;
21 };
22
23const scriptDir = path.join(process.cwd(), ".next", "static", "chunks");
24const scriptFiles = await getFiles(scriptDir);
Write File
Write File
1import { promises as fs } from 'fs';
2import path from 'path';
3
4/** ... **/
5
6// Asynchronously write to a file
7await fs.writeFile('example.txt', content, 'utf8', (err) => {
8 if (err) {
9 console.error('An error occurred while writing to the file:', err);
10 return;
11 }
12 console.log('File has been written successfully');
13});
14
15// Synchronously write to a file
16try {
17 await fs.writeFileSync('example.txt', content, 'utf8');
18 console.log('File has been written successfully');
19} catch (err) {
20 console.error('An error occurred while writing to the file:', err);
21}
Append Content
Write File
1import { promises as fs } from 'fs';
2import path from 'path';
3
4/** ... **/
5
6const additionalContent = '\nThis is the additional content to append to the file';
7
8// Asynchronously append to a file
9await fs.appendFile('example.txt', additionalContent, 'utf8', (err) => {
10 if (err) {
11 console.error('An error occurred while appending to the file:', err);
12 return;
13 }
14 console.log('Content has been appended successfully');
15});
16
17// Synchronously append to a file
18try {
19 await fs.appendFileSync('example.txt', additionalContent, 'utf8');
20 console.log('Content has been appended successfully');
21} catch (err) {
22 console.error('An error occurred while appending to the file:', err);
23}
24