NodeJS: How To Write Data As JSON To Your Machine
Tags: javascript, node, eli5
Published: 2019-08-27 19:24:16

---
title: NodeJS: How To Write Data As JSON To Your Machine
published: true
description: How To Write Data As JSON To Your Machine
tags: javascript, node, eli5
series: Intro to NodeJS
---

## Intro

So we [installed NodeJS](https://dev.to/miku86/what-is-nodejs-how-to-install-it-1900) on our machine.

Last time, we learned [how to read data](https://dev.to/miku86/nodejs-how-to-read-a-json-file-from-your-machine-1jg9) from our machine.

Now we want to learn how to write data as JSON to our machine using the [File System (FS) module](https://nodejs.org/api/fs.html).


## Write a simple script

- Open your terminal
- Create a file named `index.js`:

```sh
touch index.js
```

- Add this JavaScript code into it:

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

const FILE_NAME = 'data-write.json';
const NEW_DATA = [{ id: 2, name: 'Max' }];

const writeFileAsync = (newData) => {
  const stringifiedData = JSON.stringify(newData);

  fs.writeFile(FILE_NAME, stringifiedData, (error) => {
    if (error) {
      console.log('Async Write: NOT successful!');
      console.log(error);
    } else {
      console.log('Async Write: successful!');
      console.log(stringifiedData);
    }
  });
};

writeFileAsync(NEW_DATA);
```

Note: We are using the async [`writeFile`](https://nodejs.org/api/fs.html#fs_fs_writefile_file_data_options_callback) function to write data, because we don't want to block other tasks. You can also write data synchronously using [`writeFileSync`](https://nodejs.org/api/fs.html#fs_fs_writefilesync_file_data_options), but this could block some other tasks.

Note: You can do a lot of stuff with the File System module, therefore [read the docs of the FS module]( https://nodejs.org/api/fs.html#fs_file_system_flags).

---


## Every line explained

```js
// import the file system module
const fs = require('fs');

// save the file name of our data in a variable (increase readability)
const FILE_NAME = 'data-write.json';

// save the new data in a variable (increase readability)
const NEW_DATA = [{ id: 2, name: 'Max' }];

const writeFileAsync = (newData) => {
  // convert the  JavaScript values to a JSON string
  const stringifiedData = JSON.stringify(newData);

  // run async function to write file
  fs.writeFile(FILE_NAME, stringifiedData, (error) => {
    if (error) {
      // if there is an error, print it
      console.log('Async Write: NOT successful!');
      console.log(error);
    } else {
      console.log('Async Write: successful!');
      console.log(stringifiedData);
    }
  });
};

// run the function
writeFileAsync(NEW_DATA);
```

Note: We are using [`JSON.stringify()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify) to convert the JavaScript values to a JSON string.

---

## Run it from the terminal

- Run it: 

```sh
node index.js
```

- Result: 

```sh
Async Write: successful!
[{"id":2,"name":"Max"}]
```

---

## Next Steps

- Q: What happens, when `data-write.json` already exists?
- Q: How can we tackle this issue?
- Q: Do we need some additional error handling? (=> Docs)

---

## Further Reading

- [File System module](https://nodejs.org/api/fs.html)
- [File System Flags](https://nodejs.org/api/fs.html#fs_file_system_flags)


---

## Questions

- Did you ever use the [`fs Promises API`](https://nodejs.org/api/fs.html#fs_fs_promises_api), that uses Promises instead of Callbacks?