Nodejs filesystem: Difference between revisions
From wikinotes
Line 37: | Line 37: | ||
</syntaxhighlight> | </syntaxhighlight> | ||
== | == Promise/Callback APIs == | ||
<blockquote> | <blockquote> | ||
promise api | |||
<syntaxhighlight lang="javascript"> | <syntaxhighlight lang="javascript"> | ||
const fs = require('fs/promises'); | const fs = require('fs/promises'); | ||
await fs.rename('/var/tmp/foo.txt', '/var/tmp/bar.txt') | |||
await fs.rename('/tmp/foo.txt', '/tmp/bar.txt') | |||
// most functions do not have return values, enabling chaining .then()s | // most functions do not have return values, enabling chaining .then()s | ||
</syntaxhighlight> | </syntaxhighlight> | ||
callback api | |||
< | <syntaxhighlight lang="javascript"> | ||
</blockquote><!-- | const fs = require('fs'); | ||
fs.rename('/var/tmp/foo.txt', '/var/tmp/bar.txt', | |||
(err) => { | |||
if (err) throw err; | |||
console.log('success'); | |||
} | |||
); | |||
</syntaxhighlight> | |||
</blockquote><!-- Promise/Callback APIs --> | |||
== opening files == | == opening files == |
Revision as of 21:03, 30 July 2021
filepaths
See https://nodejs.org/api/path.html
const path = require('path'); const filepath = path.resolve('foo.txt') // relative to abspath path.dirname(filepath) // '/home/you' path.basename(filepath) // 'foo.txt' path.extname(filepath) // '.txt' // nodejs does not expand ~ // so replace it with the envvar '~/.zshrc'.replace('~', process.env.HOME)
filesystem
Use the filesystem module to interact with files (read, write, size, ..).
See https://nodejs.org/api/fs.htmlThere are 2x separate APIs for interacting with files,
and several common object classes used in return values etc.// APIs const fs = require('fs/promises'); // async/promise based const fs = require('fs'); // callback based // Common Objects fs.Dir // a directory fs.Dirent // a file/directory inside a parent dir fs.Stats // size, filetype info, last modified, permissions fs.ReadStream / fs.WriteStream // stream io fs.FSWatcher / fs.StatWatcher // fs.watch()/fs.watchFile watch a filePromise/Callback APIs
promise api
const fs = require('fs/promises'); await fs.rename('/var/tmp/foo.txt', '/var/tmp/bar.txt') // most functions do not have return values, enabling chaining .then()scallback api
const fs = require('fs'); fs.rename('/var/tmp/foo.txt', '/var/tmp/bar.txt', (err) => { if (err) throw err; console.log('success'); } );opening files
the file open modes are provided using the
flag
key in theoptions
hash./* a: append * w: write/replace * r: read * * appending '+' to any mode means read/write (ex: w+,r+,a+) */ const fs = require('fs'); fs.writeFileSync('/var/tmp/foo.txt', 'content', { flag: 'a' })const fs = require('fs'); const pfs = require('fs/promises'); const contents = 'abc\ndef'; // synchronous fs.writeFileSync('/var/tmp/foo.txt', contents) // async, callback based fs.writeFile( '/var/tmp/foo.txt', contents, err => { if (err) { console.log(err); }, }) // promise-based pfs.