Node.js

[Node.js] File System (fs) read, write, delete files, and directories

brightlightkim 2022. 4. 28. 02:04
const fs = require('fs');
//asynchronous functions

//read files
//first argument: location of the file
//function
fs.readFile('./docs/blog1.txt', (err,data) => {
	if (err) {
    	console.log(err);
    }
    console.log(data.toString());
});

// write files
// first argument: location and name of the file
// second argument: content
// third argument: callback function (after finishing writing)
fs.writeFile('./docs/blog1.txt', 'hello, world', () => {
	console.log('file was written);
);

// directories

// existsSync: return true if it exists
// first argument: location

// mkdir: make directory
// first argument: location and name of the directory
// second argument: call back function

// rmdir: remove directory
// first argument: location of the directory
// second argument: callback function
if (!fs.existsSync(./assets)) {
    fs.mkdir('./assets', (err) => {
        if (err) {
            console.log(err);
        }
        console.log('folder created');
    });
} else {
	fs.rmdir ('./assets', (err) => {
    	if (err) {
        	console.log(err)
        }
        onsole.log(folder deleted');
    })
}

//delete files

//unlink: delete the file
if (fs.existsSync(./docs/deleteme.txt)) {
    fs.unlink('./docs/deleteme.txt', (err) =>{
        if (err) {
            console.log(err)
        }
    })
}