Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Node.js fs module

Node.js fs module

Java FileNode.js Built-in Modules


The fs (File System) module is a built-in core module of Node.js, used to interact with the file system.

The fs module provides a series of methods to handle file reading, writing, deletion, and other operations.

The fs module is one of the most commonly used modules in Node.js development, especially in scenarios where local files need to be handled.


How to use the fs module?

To use the fs module, you first need to import it:

const

fs

=

require

(

'fs'

)

;

Starting from Node.js 14, you can also use the ES6 import syntax:

Example

const

fs

=

require

(

'fs'

)

;

         

// CommonJS style

// or

import

fs from

'fs'

;

             

// ES Module style


Main methods of the fs module

1. File reading

Reading files synchronously (readFileSync)

Example

const

data

=

fs.

readFileSync

(

'example.txt'

,

'utf8'

)

;

console.

log

(

data

)

;

Reading files asynchronously (readFile)

Example

fs.

readFile

(

'example.txt'

,

'utf8'

,

(

err

,

data

)

=>

{

 

if

(

err

)

throw

err

;

  console.

log

(

data

)

;

}

)

;

2. File writing

Writing files synchronously (writeFileSync)

Example

fs.

writeFileSync

(

'output.txt'

,

'Hello, Node.js!'

)

;

Writing files asynchronously (writeFile)

Example

fs.

writeFile

(

'output.txt'

,

'Hello, Node.js!'

,

(

err

)

=>

{

 

if

(

err

)

throw

err

;

  console.

log

(

'File saved'

)

;

}

)

;

3. File appending

Appending synchronously (appendFileSync)

Example

fs.

appendFileSync

(

'log.txt'

,

'New log content\n'

)

;

Appending asynchronously (appendFile)

Example

fs.

appendFile

(

'log.txt'

,

'New log content\n'

,

(

err

)

=>

{

 

if

(

err

)

throw

err

;

}

)

;

4. File status check (stat)

Example

fs.

stat

(

'example.txt'

,

(

err

,

stats

)

=>

{

 

if

(

err

)

throw

err

;

  console.

log

(

`File size

:

$

{

stats.

size

}

bytes`

)

;

  console.

log

(

`Creation time

:

$

{

stats.

birthtime

}

`

)

;

  console.

log

(

`Whether it is a file

:

$

{

stats.

isFile

(

)

}

`

)

;

  console.

log

(

`Whether it is a directory

:

$

{

stats.

isDirectory

(

)

}

`

)

;

}

)

;

5. File deletion

Deleting synchronously (unlinkSync)

Example

fs.

unlinkSync

(

'fileToDelete.txt'

)

;

Deleting asynchronously (unlink)

Example

fs.

unlink

(

'fileToDelete.txt'

,

(

err

)

=>

{

 

if

(

err

)

throw

err

;

  console.

log

(

'File deleted'

)

;

}

)

;


Promise and async/await support

Node.js 10+ provides the fs/promises module, which supports Promise-style APIs:

Example

const

fs

=

require

(

'fs'

)

.

promises

;

async

function

readFile

(

)

{

 

try

{

   

const

data

=

await fs.

readFile

(

'example.txt'

,

'utf8'

)

;

    console.

log

(

data

)

;

 

}

catch

(

err

)

{

    console.

error

(

'Error reading file:'

,

err

)

;

 

}

}

readFile

(

)

;


Streaming file operations

For large files, using Streams can improve performance:

Read streams

Example

const

readStream

=

fs.

createReadStream

(

'largeFile.txt'

,

'utf8'

)

;

readStream.

on

(

'data'

,

(

chunk

)

=>

{

  console.

log

(

'Data received:'

,

chunk.

length

)

;

}

)

;

readStream.

on

(

'end'

,

(

)

=>

{

  console.

log

(

'Read complete'

)

;

}

)

;

readStream.

on

(

'error'

,

(

err

)

=>

{

  console.

error

(

'Read error:'

,

err

)

;

}

)

;

Write streams

Example

const

writeStream

=

fs.

createWriteStream

(

'output.txt'

)

;

writeStream.

write

(

'First line of data\n'

)

;

writeStream.

write

(

'Second line of data\n'

)

;

writeStream.

end

(

'Last line of data'

)

;

writeStream.

on

(

'finish'

,

(

)

=>

{

  console.

log

(

'Write complete'

)

;

}

)

;

writeStream.

on

(

'error'

,

(

err

)

=>

{

  console.

error

(

'Write error:'

,

err

)

;

}

)

;


Directory operations

Create a directory

Example

fs.

mkdir

(

'newFolder'

,

(

err

)

=>

{

 

if

(

err

)

throw

err

;

  console.

log

(

'Directory created'

)

;

}

)

;

Read directory contents

Example

fs.

readdir

(

'./'

,

(

err

,

files

)

=>

{

 

if

(

err

)

throw

err

;

  console.

log

(

'Current directory contents:'

,

files

)

;

}

)

;

Delete directory

Example

fs.

rmdir

(

'emptyFolder'

,

(

err

)

=>

{

 

if

(

err

)

throw

err

;

  console.

log

(

'Directory deleted'

)

;

}

)

;


Best Practices

  1. Prefer asynchronous methods: Avoid blocking the event loop
  2. Error handling: Always handle possible errors
  3. Use streams to handle large files: Improve performance
  4. Path handling: Use the path module to handle cross-platform path issues
  5. Permission check: Check file/directory permissions before operating

Practical Application Examples

File copy functionality

Example

const

fs

=

require

(

'fs'

)

;

function

copyFile

(

source

,

target

,

cb

)

{

 

const

readStream

=

fs.

createReadStream

(

source

)

;

 

const

writeStream

=

fs.

createWriteStream

(

target

)

;

  readStream.

on

(

'error'

,

cb

)

;

  writeStream.

on

(

'error'

,

cb

)

;

 

  readStream.

on

(

'close'

,

(

)

=>

{

    writeStream.

end

(

)

;

    cb

(

null

)

;

 

}

)

;

 

  readStream.

pipe

(

writeStream

)

;

}

copyFile

(

'source.txt'

,

'target.txt'

,

(

err

)

=>

{

 

if

(

err

)

return

console.

error

(

'Copy failed:'

,

err

)

;

  console.

log

(

'File copied successfully'

)

;

}

)

;


Java FileNode.js Built-in Modules