# Write to file with JavaScript and Node.js

> If you're just starting with node, this will show you how to write a file to the disk using the `writeFile` function from the `fs` module.

- URL: https://graffino.com/til/write-to-file-with-javascript-and-nodejs
- Author: Zeno Popovici
- Channel: javascript
- Published: 2020-09-03
- Updated: 2026-11-21

Sometimes, as a programmer, you might need to write something to a file on the local file system. And that can be a piece of cake, case in which you'll use your favorite text editor to do it manually, but other times, it needs to be something complex and dynamic and you want your JavaScript to do it for you.

#### Here's how:

We'll first require the ```fs``` module from Node.js into our JS file.

```js
const fs = require('fs');
```

Then we'll grab our content:

```js
const content = 'Hello World!';
```

And finally we'll use the ```writeFile``` function from the ```fs``` module to populate our file. We need to provide the name of our file, the data or content to populate it with, the options (optional - for encoding, modes or flags) and a callback (also optional - to show the error message should one arise).

```js
fs.writeFile(filename, data, [options], [callback]);
```

Here I've given it the ```a+``` flag - *"Open file for reading and appending. The file is created if it does not exist."*. The encoding defaults to 'utf8' if none is given.

```js
fs.writeFile('file.txt', content, { flag: 'a+' }, (err) => {
  if (err) throw err;
});
```
