Node.js

Node.js Basics (Read & Write & Create & Remove)

brightlightkim 2022. 3. 19. 08:38

Modules & Require

//test.js
const xyz = require('./modules'); //This is importing.

const {people} = require('./modules'); //importing people. like an array.


//modules.js
const people = ['yo', 'hi', 'div'];
const ages = [25, 23, 21, 20];

module.exports = {
    people, ages
};

 

Read & Write & Directories & Delete Files

const fs = require('fs');

//Reading Files
fs.readFile('./docs/blog1.txt', (err, data) =>{
    //once this fired >> call back function.
    if (err) {
        console.log(err);
    }
    console.log(data.toString());
});

console.log('last line');

 

Write Files

//Write Files
fs.writeFile('./docs/blog3.txt', 'hello, again', () => {
    console.log('file was written'); //if exitst >> change it, if not exist >> create it
});

 

Create Directories

//directories
if (!fs.existsSync('./assets')) { //if it does not exist create it.
    fs.mkdir('./assets', (err) => {
        if (err) {
            console.log(err);
        }
        console.log('folder created');
    })
} else {
    fs.rmdir('./assets', (err) => { //remove it if it exists.
        if (err) {
            console.log(err);
        }
        console.log('folder deleted');
    })
}

 

Remove Directories

//deleting files
if (fs.existsSync('./docs/deleteme.txt')){
    fs.unlink('./docs/deleteme.txt', (err) =>{
        if (err) {
            console.log(err);
        }
        console.log("file deleted");
    }) 
}

 

 

'Node.js' 카테고리의 다른 글

[Node.js] Front End - Axios Library(Vue CLi)  (0) 2022.03.19
Node.js Express Back-end REST API  (0) 2022.03.19
Node.js Stream & Buffers  (0) 2022.03.19
Node.js Installation and Run it simply  (0) 2022.03.19
Node.js Introduction  (0) 2022.03.19