Nodejs filesystem: Difference between revisions

From wikinotes
Line 45: Line 45:
== callback api ==
== callback api ==
<blockquote>
<blockquote>
</blockquote><!-- callback api -->
== opening files ==
<blockquote>
the file open modes are provided using the <code>flag</code> param.
<syntaxhighlight lang="yaml">
a: append
w: write/replace
r: read
# appending '+' to any mode means read/write
w+,r+,a+
</syntaxhighlight>
<syntaxhighlight lang="javascript">
<syntaxhighlight lang="javascript">
const fs = require('fs');
const fs = require('fs');
const pfs = require('fs/promises');
const contents = 'abc\ndef';
const contents = 'abc\ndef';
// synchronous
fs.writeFileSync('/var/tmp/foo.txt', contents)


// async, callback based
// async, callback based
Line 54: Line 72:
})
})


// synchronous
// promise-based
fs.writeFileSync('/var/tmp/foo.txt', contents)
pfs.
</syntaxhighlight>
</syntaxhighlight>
</blockquote><!-- callback api -->
</blockquote><!-- opening files -->
</blockquote><!-- filesystem -->
</blockquote><!-- filesystem -->

Revision as of 18:01, 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.html

There are 2x separate APIs for interacting with files.

const fs = require('fs/promises'); // async/promise based
const fs = require('fs');          // callback based

promise api

const fs = require('fs/promises');

// async/await
await fs.rename('/tmp/foo.txt', '/tmp/bar.txt');

// chained promises (? can I)
fs.rename('/tmp/foo.txt', '/tmp/bar.txt')
    .then()
    .then()

callback api

opening files

the file open modes are provided using the flag param.

a: append
w: write/replace
r: read

# appending '+' to any mode means read/write
w+,r+,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.