Nodejs filesystem: Difference between revisions

From wikinotes
Line 1: Line 1:


= Paths =
= filepaths =
<blockquote>
<blockquote>
See https://nodejs.org/api/path.html
See https://nodejs.org/api/path.html
Line 15: Line 15:
'~/.zshrc'.replace('~', process.env.HOME)
'~/.zshrc'.replace('~', process.env.HOME)
</syntaxhighlight>
</syntaxhighlight>
</blockquote><!-- Paths -->
</blockquote><!-- filepaths -->
 
= filesystem =
<blockquote>
See https://nodejs.org/api/fs.html
 
There are 2x separate APIs for interacting with files.
<syntaxhighlight lang="javascript">
const fs = require('fs/promises'); // async/promise based
const fs = require('fs');          // callback based
</syntaxhighlight>
 
== promise api ==
<blockquote>
<syntaxhighlight lang="javascript">
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()
</syntaxhighlight>
</blockquote><!-- promise api -->
 
== callback api ==
<blockquote>
 
</blockquote><!-- callback api -->
</blockquote><!-- filesystem -->

Revision as of 17:47, 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

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