Node.js File System Module #52 Flashcards

1
Q

How would you require access and interaction with the file system

A

const fs = require(‘fs’)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Memorize at least some of the fs methods or refer back to this later.

A
  • fs.access( ): check if the file exists and Node can access it with its permissions
  • fs.appendFile( ): append data to a file. If the file does not exist, it’s created
  • fs.chmod( ): change the permissions of a file specified by the filename passed. Related: fs.lchmod( ), fs.fchmod()
  • fs.chown( ): change the owner and group of a file specified by the filename passed.

Related: fs.fchown( ),fs.lchown( )
fs.close( ): close a file descriptor
fs.copyFile( ): copies a file
fs.createReadStream( ): create a readable file stream
fs.createWriteStream( ): create a writable file stream
fs.link( ): create a new hard link to a file
fs.mkdir( ): create a new folder
fs.mkdtemp( ): create a temporary directory
fs.open( ): set the file mode
fs.readdir( ): read the contents of a directory
fs.readFile( ): read the content of a file.
• Related: fs.read( )
fs.readlink( ): read the value of a symbolic link
fs.realpath( ): resolve relative file path pointers (., ..) to the full path
fs.rename( ): rename a file or folder
fs.rmdir( ): remove a folder
fs.stat( ): returns the status of the file identified by the filename passed. Related: fs.fstat( ), fs.lstat( )
fs.symlink( ): create a new symbolic link to a file
fs.truncate( ): truncate to the specified length the file identified by the filename passed. Related: fs.ftruncate( )
fs.unlink( ): remove a file or a symbolic link
fs.unwatchFile( ): stop watching for changes on a file
fs.utimes( ): change the timestamp of the file identified by the filename passed. Related: fs.futimes()
fs.watchFile( ): start watching for changes on a file. Related: fs.watch( )
fs.writeFile( ): write data to a file. Related: fs.write( )

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

The full list of methods that can be used under the fs module are asynchronous by default. How would you make them synchronous if needed ?

A

Append Sync to the method. Example:
For example:

fs. rename( )
fs. renameSync( )
fs. write( )
fs. writeSync( )
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

How can you access the “path” module in Node.js?

A

Require it as below:

const path = require(‘path’)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What is path.sep?

A

It’s simply the path segment separator /

/ Mac/Linux
\ Windows

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What does the path.basename( ) method do?

A

Return the last portion of a path. A second parameter can filter out the file extension:

require(‘path’).basename(‘/test/something’) //something
require(‘path’).basename(‘/test/something.txt’) //something.txt
require(‘path’).basename(‘/test/something.txt’, ‘.txt’) //something

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What does the path.dirname( ) method do?

A

Return the directory part of a path:

require(‘path’).dirname(‘/test/something’) // /test
require(‘path’).dirname(‘/test/something/file.txt’) // /test/something

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What does the path.extname( ) method do?

A

Return the extension part of a path

require(‘path’).extname(‘/test/something’) // ‘’
require(‘path’).extname(‘/test/something/file.txt’) // ‘.txt’

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What does the path.isAbsolute( ) method do?

A

Returns true if it’s an absolute path

require(‘path’).isAbsolute(‘/test/something’) // true
require(‘path’).isAbsolute(‘./test/something’) // false

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What does the path.join( ) method do?

A

Joins two or more parts of a path:

const name = 'flavio'
require('path').join('/', 'users', name, 'notes.txt') //'/users/flavio/notes.txt'
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What does the path.normalize( ) method do?

A

Tries to calculate the actual path when it contains relative specifiers like . or .., or double slashes:

require(‘path’).normalize(‘/users/flavio/..//test.txt’) ///users/test.txt

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What does the path.parse( ) method do?

A

Parses a path to an object with the segments that compose it:

root: the root
dir: the folder path starting from the root
base: the file name + extension
name: the file name
ext: the file extension

Example:

require(‘path’).parse(‘/users/test.txt’)
results in

{
  root: '/',
  dir: '/users',
  base: 'test.txt',
  ext: '.txt',
  name: 'test'
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What does the path.relative( ) method do?

A

Accepts 2 paths as arguments. Returns the relative path from the first path to the second, based on the current working directory.

Example:

require(‘path’).relative(‘/Users/flavio’, ‘/Users/flavio/test.txt’) //’test.txt’
require(‘path’).relative(‘/Users/flavio’, ‘/Users/flavio/something/test.txt’) //’something/test.txt’

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What does the path.resolve( ) method do?

A

You can get the absolute path calculation of a relative path using path.resolve():

path.resolve(‘flavio.txt’) //’/Users/flavio/flavio.txt’ if run from my home folder

By specifying a second parameter, resolve will use the first as a base for the second:

path.resolve(‘tmp’, ‘flavio.txt’)//’/Users/flavio/tmp/flavio.txt’ if run from my home folder

If the first parameter starts with a slash, that means it’s an absolute path:

path.resolve(‘/etc’, ‘flavio.txt’)//’/etc/flavio.txt’

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

What is the main use for the ‘OS’ module? And like other modules, how is it accessed?

A

This module provides many functions that you can use to retrieve information from the underlying operating system and the computer the program runs on, and interact with it.

REQUIRE
const os = require('os')
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

How can you find what the delimiter sequence is on a user’s machine?

A

By calling the os.EOL method. It gives the line delimiter sequence. It’s \n on Linux and macOS, and \r\n on Windows.

*This is a key method that assists in handling files.

17
Q

What information does os.constants.signals tell you?

A

I gives all the constants related to handling process signals, like SIGHUP, SIGKILL and so on.

*This is a key method that assists in handling files.

18
Q

What is os.constants.errno used for?

A

It sets the constants for error reporting, like EADDRINUSE, EOVERFLOW and more.

*This is a key method that assists in handling files.

19
Q

What does the os.arch( ) method do?

A

Return the string that identifies the underlying architecture, like arm, x64, arm64.

20
Q

What does the os.cpus( ) method do?

A

Return information on the CPUs available on your system.

Example:

[ { model: 'Intel(R) Core(TM)2 Duo CPU     P8600  @ 2.40GHz',
    speed: 2400,
    times:
     { user: 281685380,
       nice: 0,
       sys: 187986530,
       idle: 685833750,
       irq: 0 } },
  { model: 'Intel(R) Core(TM)2 Duo CPU     P8600  @ 2.40GHz',
    speed: 2400,
    times:
     { user: 282348700,
       nice: 0,
       sys: 161800480,
       idle: 703509470,
       irq: 0 } } ]
21
Q

What does the os.endianness( ) method do?

A

Return BE or LE depending if Node was compiled with Big Endian or Little Endian. Huh? Say What?

22
Q

What does the os.freemem( ) method do?

A

Return the number of bytes that represent the free memory in the system.

23
Q

What does the os.homedir( ) method do?

A

Return the path to the home directory of the current user.

Example:

‘/Users/flavio’

24
Q

What does the os.hostname( ) method do?

A

Return the hostname.

25
Q

What does the os.loadavg( ) method do?

A

Return the calculation made by the operating system on the load average.

It only returns a meaningful value on Linux and macOS.

Example:

[ 3.68798828125, 4.00244140625, 11.1181640625 ]

26
Q

What does the os.networkInterfaces( ) method d

A

Returns the details of the network interfaces available on your system. The example provided is TL;DR

Just know it provides IP Addresses, MAC Addresses, Network protocols etc.

27
Q

How would you find the OS your user is utilizing?

A

os.type( )

28
Q

What is the simplest way to read a file with Node.js?

A

The simplest way to read a file in Node is to use the fs.readFile() method, passing it the file path and a callback function that will be called with the file data (and the error):

Both fs.readFile() and fs.readFileSync() read the full content of the file in memory before returning the data.

This means that big files are going to have a major impact on your memory consumption and speed of execution of the program.

const fs = require(‘fs’)

fs.readFile('/Users/flavio/test.txt', (err, data) => {
  if (err) {
    console.error(err)
    return
  }
  console.log(data)
})

Alternatively, you can use the synchronous version fs.readFileSync():

const fs = require(‘fs’)

try {
  const data = fs.readFileSync('/Users/flavio/test.txt', 'utf8')
  console.log(data)
} catch (err) {
  console.error(err)
}
29
Q

What is the best way to write a file with Node.js?

A

The easiest way to write to files in Node.js is to use the fs.writeFile() API.

Example:

const fs = require(“fs”)

const content = “Some content!”

fs.writeFile("/Users/flavio/test.txt", content, (err) => {
  if (err) {
    console.error(err)
    return
  }
  //file written successfully
}
30
Q

How can you inspect a file and get information about it?

A

using the stat() method provided by the fs module.

You call it passing a file path, and once Node gets the file details it will call the callback function you pass, with 2 parameters: an error message, and the file stats:

const fs = require("fs")
fs.stat("/Users/flavio/test.txt", (err, stats) => {
  if (err) {
    console.error(err)
    return
  }
  //we have access to the file stats in `stats`
})
31
Q

How can you check if a directory exists?

A

Use fs.access() to check if the folder exists and Node can access it with its permissions.

32
Q

How can you create a new directory using Node.ja?

A

Use fs.mkdir() or fs.mkdirSync() to create a new folder.

const fs = require(‘fs’)

const dir = ‘/Users/flavio/test’

try {
  if (!fs.existsSync(dir)){
    fs.mkdirSync(dir)
  }
} catch (err) {
  console.error(err)
}
33
Q

What if you wanted to read the content of a directory?

A

Use fs.readdir() or fs.readdirSync to read the contents of a directory.

Example:

const fs = require('fs')
const path = require('path')
const folderPath = '/Users/flavio'
fs.readdirSync(folderPath)
34
Q

How can you rename a directory?

A

const fs = require(‘fs’)

fs.rename('/Users/flavio', '/Users/roger', err => {
  if (err) {
    console.error(err)
    return
  }
  //done
})
35
Q

How would you remove a directory with node.js?

A

Use fs.rmdir( ) Luckily, these expressions look a lot like Linux in terms of naming conventions.

36
Q

Yikes this chapter =

A

BRUTALLY Mindnumbing.