open()
method from the fs
module to open a file: const fs = require('fs') fs.open('/Users/flavio/test.txt', 'r', (err, fd) => { //fd - })
r
, used when calling the fs.open()
method. This is the flag that tells the system that the file is being opened for reading. Here are some more flags that are often used when working with this and some other methods:r+
- open file for reading and writing.w+
- open the file for reading and writing by setting the stream pointer to the beginning of the file. If the file does not exist, it is created.a
- open file for writing by setting the stream pointer to the end of the file. If the file does not exist, it is created.a+
- open the file for reading and writing by setting the stream pointer to the end of the file. If the file does not exist, it is created.fs.openSync()
, which, instead of providing a file descriptor in a callback, returns it: const fs = require('fs') try { const fd = fs.openSync('/Users/flavio/test.txt', 'r') } catch (err) { console.error(err) }
stat()
method from the fs
module.stat()
method. Here's what it looks like: const fs = require('fs') fs.stat('/Users/flavio/test.txt', (err, stats) => { if (err) { console.error(err) return } // `stats` })
const fs = require('fs') try { const stats = fs.statSync ('/Users/flavio/test.txt') } catch (err) { console.error(err) }
stats
constant. What is this information? In fact, the corresponding object provides us with a large number of useful properties and methods:.isFile()
and .isDirectory()
methods allow, respectively, to find out if the file being examined is a regular file or a directory..isSymbolicLink()
method lets you know if a file is a symbolic link..size
property. const fs = require('fs') fs.stat('/Users/flavio/test.txt', (err, stats) => { if (err) { console.error(err) return } stats.isFile() //true stats.isDirectory() //false stats.isSymbolicLink() //false stats.size //1024000 //= 1MB })
/users/flavio/file.txt
C:\users\flavio\file.txt
path
module, designed to work with file paths. Before using this module in the program, it must be connected: const path = require('path')
path
module, you can, in a convenient form for perception and further processing, to learn the details about this path. It looks like this: const notes = '/users/flavio/notes.txt' path.dirname(notes) // /users/flavio path.basename(notes) // notes.txt path.extname(notes) // .txt
notes
line, the path to the file is stored. The following methods of the path
module are used to parse the path
:dirname()
- returns the parent directory of the file.basename()
- returns the file name.extname()
- returns the file extension..basename()
method and passing to it the second argument representing the extension: path.basename(notes, path.extname(notes)) //notes
path.join()
method: const name = 'flavio' path.join('/', 'users', name, 'notes.txt') //'/users/flavio/notes.txt'
path.resolve()
method: path.resolve('flavio.txt') //'/Users/flavio/flavio.txt'
/flavio.txt
to the path leading to the current working directory. If, when calling this method, we pass another parameter representing the path to the folder, the method uses it as the basis for determining the absolute path: path.resolve('tmp', 'flavio.txt') // '/Users/flavio/tmp/flavio.txt'
path.resolve('/etc', 'flavio.txt') // '/etc/flavio.txt'
path.normalize()
. It allows you to find the real file path using a path that contains relative path specifiers like a dot ( .
), Two dots ( ..
), or two slashes: path.normalize('/users/flavio/..//test.txt') // /users/test.txt
resolve()
and normalize()
methods do not verify the existence of a directory. They simply find the path based on the data passed to them.fs.readFile()
method with passing it the path to the file and a callback that will be called with passing it the file data (or the error object): fs.readFile('/Users/flavio/test.txt', (err, data) => { if (err) { console.error(err) return } console.log(data) })
fs.readFileSync()
: const fs = require('fs') try { const data = fs.readFileSync('/Users/flavio/test.txt') console.log(data) } catch (err) { console.error(err) }
utf8
encoding is used when reading files, but the encoding can also be set independently by passing the corresponding parameter to the method.fs.readFile()
and fs.readFileSync()
methods read the entire contents of the file into memory. This means that working with large files using these methods will seriously affect the memory consumption of your application and will affect its performance. If you need to work with such files, it is best to use streams.fs.writeFile()
method: const fs = require('fs') const content = 'Some content!' fs.writeFile('/Users/flavio/test.txt', content, (err) => { if (err) { console.error(err) return } // })
fs.writeFileSync()
: const fs = require('fs') const content = 'Some content!' try { const data = fs.writeFileSync('/Users/flavio/test.txt', content) // } catch (err) { console.error(err) }
fs.writeFile('/Users/flavio/test.txt', content, { flag: 'a+' }, (err) => {})
fs.appendFile()
method (and its synchronous version - fs.appendFileSync()
) is conveniently used to fs.appendFileSync()
data to the end of the file: const content = 'Some content!' fs.appendFile('file.log', content, (err) => { if (err) { console.error(err) return } //! })
fs
module provides the developer with many convenient methods that can be used to work with directories.fs.access()
method.fs.mkdir()
and fs.mkdirSync()
methods: const fs = require('fs') const folderName = '/Users/flavio/test' try { if (!fs.existsSync(dir)){ fs.mkdirSync(dir) } } catch (err) { console.error(err) }
fs.readdir()
and fs.readdirSync()
methods. In this example, the contents of the folder are read — that is, information on which files and subdirectories are in it, and the return of their relative paths: const fs = require('fs') const path = require('path') const folderPath = '/Users/flavio' fs.readdirSync(folderPath)
fs.readdirSync(folderPath).map(fileName => { return path.join(folderPath, fileName) }
const isFile = fileName => { return fs.lstatSync(fileName).isFile() } fs.readdirSync(folderPath).map(fileName => { return path.join(folderPath, fileName)).filter(isFile) }
fs.rename()
and fs.renameSync()
methods. The first parameter is the current path to the folder, the second is the new one: const fs = require('fs') fs.rename('/Users/flavio', '/Users/roger', (err) => { if (err) { console.error(err) return } // })
fs.renameSync()
method: const fs = require('fs') try { fs.renameSync('/Users/flavio', '/Users/roger') } catch (err) { console.error(err) }
fs.rmdir()
or fs.rmdirSync()
methods. It should be noted that deleting a folder in which there is something, the task is somewhat more complicated than deleting an empty folder. If you need to delete such folders, use the fs-extra package, which is very popular and well supported. It is a replacement for the fs
module, expanding its capabilities.remove()
method from the fs-extra
package can remove folders that already have something in it. npm install fs-extra
const fs = require('fs-extra') const folder = '/Users/flavio' fs.remove(folder, err => { console.error(err) })
fs.remove(folder).then(() => { // }).catch(err => { console.error(err) })
async function removeFolder(folder) { try { await fs.remove(folder) // } catch (err) { console.error(err) } } const folder = '/Users/flavio' removeFolder(folder)
fs
module methods used when working with the file system. In fact, it contains a lot more useful. Recall that it does not need to be installed, in order to use it in the program, it is enough to connect it: const fs = require('fs')
fs.access()
: checks the existence of the file and the ability to access it, taking into account permissions.fs.appendFile()
: fs.appendFile()
data to the file. If the file does not exist, it will be created.fs.chmod()
: changes permissions for a given file. Similar methods: fs.lchmod()
, fs.fchmod()
.fs.chown()
: changes the owner and group for the specified file. Similar methods: fs.fchown()
, fs.lchown()
.fs.close()
: closes the file descriptor.fs.copyFile()
: copies the file.fs.createReadStream()
: creates a file reading stream.fs.createWriteStream()
: creates a stream writing a file.fs.link()
: creates a new hard link to the file.fs.mkdir()
: creates a new directory.fs.mkdtemp()
: creates a temporary directory.fs.open()
: opens the file.fs.readdir()
: reads the contents of a directory.fs.readFile()
: reads the contents of the file. Similar method: fs.read()
.fs.readlink()
: reads the value of a symbolic link.fs.realpath()
: allows a relative path to a file constructed using symbols .
and ..
, in full.fs.rename()
: renames a file or folder.fs.rmdir()
: deletes the folder.fs.stat()
: returns file information. Similar methods: fs.fstat()
, fs.lstat()
.fs.symlink()
: creates a new symbolic link to the file.fs.truncate()
: truncates the file to the specified length. Similar method: fs.ftruncate()
.fs.unlink()
: removes a file or a symbolic link.fs.unwatchFile()
: disables the monitoring of file changes.fs.utimes()
: changes the timestamp of the file. A similar method: fs.futimes()
.fs.watchFile()
: includes monitoring for file changes. A similar method: fs.watch()
.fs.writeFile()
: writes data to a file. A similar method: fs.write()
.fs
module is the fact that all its methods, by default, are asynchronous, but there are also their synchronous versions, whose names are obtained by adding the word Sync
to the names of asynchronous methods.fs.rename()
fs.renameSync()
fs.write()
fs.writeSync()
fs.rename()
method. Here is an asynchronous version of this method using callbacks: const fs = require('fs') fs.rename('before.json', 'after.json', (err) => { if (err) { return console.error(err) } // })
try/catch
used for error handling: const fs = require('fs') try { fs.renameSync('before.json', 'after.json') // } catch (err) { console.error(err) }
const path = require('path')
path.sep
property of this module provides the symbol used to separate the segments of the path ( \
on Windows and /
on Linux and macOS), and the path.delimiter
property gives the symbol used to separate several paths from each other ( ;
on Windows and :
on Linux and macOS).path
module. require('path').basename('/test/something') //something require('path').basename('/test/something.txt') //something.txt require('path').basename('/test/something.txt', '.txt') //something
require('path').dirname('/test/something') // /test require('path').dirname('/test/something/file.txt') // /test/something
require('path').extname('/test/something') // '' require('path').extname('/test/something/file.txt') // '.txt'
require('path').isAbsolute('/test/something') // true require('path').isAbsolute('./test/something') // false
const name = 'flavio' require('path').join('/', 'users', name, 'notes.txt') //'/users/flavio/notes.txt'
.
, ..
and //
: require('path').normalize('/users/flavio/..//test.txt') ///users/test.txt
root
: root directory.dir
: file path starting from the root directorybase
: file name and extension.name
: file name.ext
: file extension. require('path').parse('/users/test.txt')
{ root: '/', dir: '/users', base: 'test.txt', ext: '.txt', name: 'test' }
require('path').relative('/Users/flavio', '/Users/flavio/test.txt') //'test.txt' require('path').relative('/Users/flavio', '/Users/flavio/something/test.txt') //'something/test.txt'
path.resolve('flavio.txt') //'/Users/flavio/flavio.txt' .
fs
and path
modules that are used to work with the file system. In the next part of this series, where it ends, we will discuss the modules os
, events
, http
, talk about working with threads and database management systems in Node.js.Source: https://habr.com/ru/post/424969/
All Articles