5,336
edits
No edit summary |
|||
Line 35: | Line 35: | ||
[https://www.npmjs.com/package/fs-extra fs-extra] adds additional commands for accessing the filesystem such as copying and moving files. | [https://www.npmjs.com/package/fs-extra fs-extra] adds additional commands for accessing the filesystem such as copying and moving files. | ||
<syntaxhighlight lang="js"> | <syntaxhighlight lang="js"> | ||
const fs = require('fs-extra') | const fs = require('fs-extra'); | ||
const path = require('path'); | |||
// Synchronous functions | // Synchronous functions | ||
// Only in fs-extra | |||
// Remove file or folder (rm -rf) | // Remove file or folder (rm -rf) | ||
Line 45: | Line 48: | ||
// Creates a directory if it doesn't exist | // Creates a directory if it doesn't exist | ||
// This example will create folder1 and folder2 if they don't exist | // This example will create folder1 and folder2 if they don't exist | ||
fs.ensureDirSync('/tmp/folder1/folder2/'); | fs.ensureDirSync('/tmp/folder1/folder2'); | ||
// Available in node's native 'fs' | |||
// List all files and folders in a directory | |||
fs.readdirSync('/tmp'); | |||
// Ensure file exists | |||
try { | |||
fs.accessSync('etc/passwd', fs.constants.R_OK | fs.constants.W_OK); | |||
console.log('can read/write'); | |||
} catch (err) { | |||
console.error('no access!'); | |||
} | |||
// Read an entire text file as a string | |||
fs.readFileSync('temp.txt', 'utf8'); | |||
</syntaxhighlight> | </syntaxhighlight> |