Nodejs filesystem: Difference between revisions

From wikinotes
 
(13 intermediate revisions by the same user not shown)
Line 1: Line 1:
= Documentation =
<blockquote>
{| class="wikitable"
|-
| path docs || https://nodejs.org/api/path.html
|-
| fs docs || https://nodejs.org/api/fs.html
|-
|}
</blockquote><!-- Documentation -->


= filepaths =
= filepaths =
Line 12: Line 23:


// nodejs does not expand ~
// nodejs does not expand ~
// so replace it with the envvar
// so replace it with the envvar or os.homedir()
'~/.zshrc'.replace('~', process.env.HOME)
'~/.zshrc'.replace('~', process.env.HOME)
'~/.zshrc'.replace('~', os.homedir())
</syntaxhighlight>
</syntaxhighlight>
</blockquote><!-- filepaths -->
</blockquote><!-- filepaths -->
Line 37: Line 49:
</syntaxhighlight>
</syntaxhighlight>


== promise api ==
== promise/callback APIs ==
<blockquote>
<blockquote>
promise api
<syntaxhighlight lang="javascript">
<syntaxhighlight lang="javascript">
const fs = require('fs/promises');
const fs = require('fs/promises');


// async/await
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
</syntaxhighlight>
 
callback api
<syntaxhighlight lang="javascript">
const fs = require('fs');


// I don't believe these functions have return values enabling them to be chained in .then()
fs.rename('/var/tmp/foo.txt', '/var/tmp/bar.txt',
  (err) => {
    if (err) throw err;
    console.log('success');
  }
);
</syntaxhighlight>
</syntaxhighlight>
</blockquote><!-- promise api -->
</blockquote><!-- Promise/Callback APIs -->


== callback api ==
== manipulating files ==
<blockquote>
<blockquote>
</blockquote><!-- callback api -->
<syntaxhighlight lang="javascript">
// test files, list dirs
fs.existSync('/var/tmp/dir')    // true
fs.readdirSync('/var/tmp/dir')  // ['foo.txt', 'bar.txt']
 
// remove file
fs.rmdir('/var/foo', { recursive: true, force: true })
fs.rmdirSync('/var/foo')
 
// recursively delete directory/children
 
// move file
fs.rename('/var/foo', '/var/bar')


== opening files ==
// create directory
fs.mkdir('/var/tmp/dir')
fs.mkdirSync('/var/tmp/dir')
</syntaxhighlight>
</blockquote><!-- manipulating files -->
 
== opening/writing files ==
<blockquote>
<blockquote>
the file open modes are provided using the <code>flag</code> key in the <code>options</code> hash.
The file open modes are provided using the <code>flag</code> key in the <code>options</code> hash.<br>
Alternatively, you may be interested in [[nodejs streams]].
 
<syntaxhighlight lang="javascript">
<syntaxhighlight lang="javascript">
/* a: append
/* a: append
Line 76: Line 120:


// async, callback based
// async, callback based
fs.writeFile('/var/tmp/foo.txt', contents, err => {
fs.writeFile(
    if (err) { console.log(err); }
  '/var/tmp/foo.txt',  
  contents,  
  err => { if (err) { console.log(err); },
})
})


Line 84: Line 130:
</syntaxhighlight>
</syntaxhighlight>
</blockquote><!-- opening files -->
</blockquote><!-- opening files -->
== file info ==
<blockquote>
<syntaxhighlight lang="javascript">
const fs = require('fs/promises');
await let info = fs.stat('foo.txt')
// .. info.size
// .. info.uid
// .. info.mode (BigInt, convert to octal)
// ..
</syntaxhighlight>
</blockquote><!-- file info -->
</blockquote><!-- filesystem -->
</blockquote><!-- filesystem -->

Latest revision as of 02:44, 6 August 2021

Documentation

path docs https://nodejs.org/api/path.html
fs docs https://nodejs.org/api/fs.html

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 or os.homedir()
'~/.zshrc'.replace('~', process.env.HOME)
'~/.zshrc'.replace('~', os.homedir())

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,
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 file

promise/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()s

callback api

const fs = require('fs');

fs.rename('/var/tmp/foo.txt', '/var/tmp/bar.txt', 
  (err) => { 
    if (err) throw err; 
    console.log('success');
  }
);

manipulating files

// test files, list dirs
fs.existSync('/var/tmp/dir')    // true
fs.readdirSync('/var/tmp/dir')  // ['foo.txt', 'bar.txt']

// remove file
fs.rmdir('/var/foo', { recursive: true, force: true })
fs.rmdirSync('/var/foo')

// recursively delete directory/children

// move file
fs.rename('/var/foo', '/var/bar')

// create directory
fs.mkdir('/var/tmp/dir')
fs.mkdirSync('/var/tmp/dir')

opening/writing files

The file open modes are provided using the flag key in the options hash.
Alternatively, you may be interested in nodejs streams.

/* 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.

file info

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

await let info = fs.stat('foo.txt')
// .. info.size
// .. info.uid
// .. info.mode (BigInt, convert to octal)
// ..