2022-04-23 13:26:53 +01:00
|
|
|
---
|
2022-09-06 15:44:40 +01:00
|
|
|
categories:
|
|
|
|
- Programming Languages
|
2022-04-23 13:26:53 +01:00
|
|
|
tags:
|
|
|
|
- backend
|
|
|
|
- node-js
|
|
|
|
---
|
|
|
|
|
2022-05-26 20:00:04 +01:00
|
|
|
# I/O with files
|
2022-09-06 15:44:40 +01:00
|
|
|
|
2022-04-23 13:26:53 +01:00
|
|
|
## Read file from directory (JSON)
|
|
|
|
|
2022-09-06 15:44:40 +01:00
|
|
|
```js
|
|
|
|
const fs = require('fs');
|
2022-04-23 13:26:53 +01:00
|
|
|
|
|
|
|
// Get raw JSON
|
2022-09-06 15:44:40 +01:00
|
|
|
let inputJson = fs.readFileSync('source.json');
|
2022-04-23 13:26:53 +01:00
|
|
|
|
|
|
|
// Convert to JS
|
|
|
|
let data = JSON.parse(inputJson);
|
2022-09-06 15:44:40 +01:00
|
|
|
```
|
2022-04-23 13:26:53 +01:00
|
|
|
|
|
|
|
## Write file to directory (JSON)
|
|
|
|
|
2022-09-06 15:44:40 +01:00
|
|
|
```js
|
2022-04-23 13:26:53 +01:00
|
|
|
let newFile = 'new.json';
|
|
|
|
|
2022-09-06 15:44:40 +01:00
|
|
|
// Write JS object to JSON file as JSON
|
2022-04-23 13:26:53 +01:00
|
|
|
fs.writeFileSync(writePath, JSON.stringify(alienblood));
|
2022-09-06 15:44:40 +01:00
|
|
|
```
|
2022-04-23 13:26:53 +01:00
|
|
|
|
|
|
|
## Delete file from directory
|
|
|
|
|
2022-09-06 15:44:40 +01:00
|
|
|
```js
|
2022-04-23 13:26:53 +01:00
|
|
|
let filePath = 'file-to-delete.json';
|
|
|
|
fs.unlinkSync(filePath);
|
2022-09-06 15:44:40 +01:00
|
|
|
```
|
2022-04-23 13:26:53 +01:00
|
|
|
|
|
|
|
## Applications
|
|
|
|
|
|
|
|
### Overwrite file
|
|
|
|
|
2022-09-06 15:44:40 +01:00
|
|
|
```js
|
2022-04-23 13:26:53 +01:00
|
|
|
if (fs.existsSync(writePath)) {
|
2022-09-06 15:44:40 +01:00
|
|
|
fs.unlinkSync(writePath);
|
|
|
|
fs.writeFileSync(writePath, JSON.stringify(someJS));
|
|
|
|
} else {
|
|
|
|
fs.writeFileSync(writePath, JSON.stringif(someJS));
|
|
|
|
}
|
|
|
|
```
|