-- JanisRancourt - 28 Sep 2020

The Node JS File System is a feature built into Node which allows you to access other files and directories from within your script.


In order to use it, you will need to require the `fs` module.

const fs = require('fs')


You can create a directory with `fs.mkdir()`. The basic syntax is below.

fs.mkdir('my-folder', (error) => { if (error) throw error console.log('made directory successfully') })

This will create a directory called `my-folder` in the current working directory, unless there's an error. If an error occurs, it will throw the error. It will log to the console when it's done.


You can create a file with `fs.writeFile()`. The basic syntax is below.

fs.writeFile('my-folder/my-file.txt', 'hello world', (error) => { if (error) throw error console.log('file created successfully') })

This will create a file called `my-file.txt` in the `my-folder` directory, unless there's an error. If an error occurs, it will throw the error. It will log to the console when it's done.


You can read the contents of a file with `fs.readFile()`. The basic syntax is below.

fs.readFile('my-folder/my-file.txt', 'UTF-8', (error, contents) => { if (error) throw error console.log(contents) })

This will read the file `my-file.txt` in the `my-folder` directory, unless there's an error. If an error occurs, it will throw the error. It will log the contents of the file to the console when it's done, using `UTF-8` encoding. If following along here, it would log `hello world`, as that's what we put in that file in the above example.


Further reading can be found in the Node JS docs, which go much further into depth.

https://nodejs.org/dist/latest-v14.x/docs/api/fs.html
Topic revision: r1 - 28 Sep 2020, JanisRancourt
© 2020 Ultranauts - 75 Broad Street, 2nd Floor, Suite 206, New York, NY 10004 - info@ultranauts.co