Many front-end students do not have server or client experience and are afraid of Node operation, which is unnecessary.
As god Winter said: the so-called programming, nothing more than IO. The Web front-end in general deals with input and output of various apis based on HTTP and browser (or host) local caches. As a server platform, Node is not facing the browser, but the server itself, so Node can operate, is the whole server resources, including the front-end is not often in contact with network IO, disk IO, database IO and so on; To learn these operations, take a look at the Node documentation, write a demo and play with it. You’ll get the hang of it in no time.
Further, we package front-end projects based on webpack/gulp and other tools. That is, we test, reconstruct and compress code resources on our computers through Node and various toolkits, and output code packages with different requirements. If you put this process on the server side and integrate the release review process, it’s what we call CI/CD.
This article focuses on the basic interface capabilities that Come with Node.
process
Node Main process.
process.env
% node Welcome to node.js v15.12.0.type".help" for more information.
> process.env
Copy the code
Process is the main node process, and process.env contains various runtime environment variables. Among them are commonly used
process.env.PWD // The directory in which the script is started
process.env.HOME // Current user directory
process.env.USER // The current user name
process.env.SHELL // Name of the current terminal
process.env.PATH // System global variables
Copy the code
process.argv
The full command + arguments executed by the script.
path
// js
const path = require('path')
Copy the code
Path is used to deal with various local path problems.
Path. join Path stitching
> path.join('/baseDir'.'a'.'b')
'/baseDir/a/b'
> path.join('/baseDir'.'a'.'.. /b')
'/baseDir/b'
Copy the code
Path. resolve Resolve the path
> path.resolve('/baseDir'.'a'.'b')
'/baseDir/a/b'
> path.resolve('/baseDir'.'a'.'.. /b')
'/baseDir/b'
Copy the code
Path. relative Relative path
> path.relative('/baseDir'.'/baseDir/a')
'a'
> path.relative('/baseDir'.'/someElseDir/a')
'.. /someElseDir/a'
> path.relative('/baseDir/a/aa'.'/baseDir/b/bb')
'.. /.. /b/bb'
Copy the code
Path. dirname Gets the name of the directory
> path.dirname('/baseDir/a/b')
'/baseDir/a'
> path.dirname('/baseDir/a/b/')
'/baseDir/a'
Copy the code
The path format of Windows and Mac Linux is different. Therefore, you must use path when dealing with path problems. Do not try to concatenate paths yourself unless necessary.
fs
const fs = require('fs')
Copy the code
Fs stands for File System, so its name means a tool for manipulating files. For convenience, only asynchronous methods are covered here. Add Sync directly to the synchronization method. For details, see the Node documentation.
Whether the fs.exists file or directory exists
> fs.exists('/baseDir/a/b.html'.r= > console.log('exists', r))
> exists false // The file does not exist
> fs.exists('~/11111.zip'.r= > console.log('exists', r))
> exists false // ~/ is not supported
> fs.exists(path.join(process.env.HOME, '11111.zip'), r= > console.log('exists', r))
> exists true // Concatenate the full address with environment variables
> fs.exists(process.env.HOME, r= > console.log('exists', r))
> exists true // You can also check whether the directory exists
Copy the code
Fs. stat Path details
File Details
> fs.stat(path.join(process.env.HOME, '11111.zip'), (err,stat) = > console.log('\nstat', stat, '\nerror', err))
stat Stats {
dev: 16777221.mode: 33188.nlink: 1.uid: 501.gid: 20.rdev: 0.blksize: 4096.ino: 12006418.size: 332419104.blocks: 649264.atimeMs: 1615184984501.856.mtimeMs: 1615184993657.0806.ctimeMs: 1615185011988.9607.birthtimeMs: 1615184984501.856.atime: 2021-03-08T06:29:44.502Z,
mtime: 2021-03-08T06:29:53.657Z,
ctime: 2021-03-08T06:30:11.989Z,
birthtime: 2021-03-08T06:29:44.502Z
}
error null
Copy the code
Directory Details
> fs.stat(process.env.HOME, (err,stat) = > console.log('\nstat', stat, '\nerror', err))
stat Stats {
dev: 16777221.mode: 16877.nlink: 78.uid: 501.gid: 20.rdev: 0.blksize: 4096.ino: 363143.size: 2496.blocks: 0.atimeMs: 1624841990808.2407.mtimeMs: 1624841990597.5269.ctimeMs: 1624841990597.5269.birthtimeMs: 1603169031408.2742.atime: 2021-06-28T00:59:50.808Z,
mtime: 2021-06-28T00:59:50.598Z,
ctime: 2021-06-28T00:59:50.598Z,
birthtime: 2020-10-20T04:43:51.408Z
}
error null
Copy the code
Path does not exist
> fs.stat('/baseDir/a/b'.(err,stat) = > console.log('\nstat', stat, '\nerror', err))
stat undefined
error [Error: ENOENT: no such file or directory, stat '/baseDir/a/b'] {
errno: -2.code: 'ENOENT'.syscall: 'stat'.path: '/baseDir/a/b'
}
Copy the code
Determining the path type
> fs.stat(process.env.HOME, (err,stat) = > console.log('\nisDir', stat.isDirectory(), 'isFile', stat.isFile(), '\nerror', err))
isDir true isFile false
error null
Copy the code
> fs.stat(path.join(process.env.HOME, '11111.zip'), (err,stat) = > console.log('\nisDir', stat.isDirectory(), 'isFile', stat.isFile(), '\nerror', err))
isDir false isFile true
error null
Copy the code
PS: According to my own impression, in differentnode
In version, fs.stat feedback is different for non-existent paths. Recommended to use firstfs.exists
Judge existence.
Fs. readFile Reads the file content
Before using this method, you should make sure that the file exists.
> fs.readFile(path.join(process.env.HOME, 'testnpm/build.js'), (err, content) = > console.log('\ncontent',content,'\nerror', err))
content <Buffer 63 6f 6e 73 6f 6c 65 2e 6c 6f 67 28 27 62 75 69 6c 64 27 29 0a>
error null
Copy the code
The above code does not specify an encoding format, so the file contents are returned in Buffer binary format. Read the file as text using UTF-8 format below:
> fs.readFile(path.join(process.env.HOME, 'testnpm/build.js'), 'utf-8'.(err, content) = > console.log('\ncontent',content,'\nerror', err))
content console.log('build')
error null
Copy the code
Fs. writeFile Writes file contents
Before using this method, you should make sure that the file exists.
> fs.writeFile(path.join(process.env.HOME, 'a.txt'), 'hello fs'.err= > console.log('\nerr', err))
err null
Copy the code
# view file
% cat a.txt
hello fs
Copy the code
Fs. unlink Deletes a file
> fs.unlink(path.join(process.env.HOME, 'a.txt'), err= > console.log(err))
> null
Copy the code
If the directory does not exist, an error is reported:
> fs.unlink('/xxxxxx/xxxxxx.js'.err= > console.log(err))
> [Error: ENOENT: no such file or directory, unlink '/xxxxxx/xxxxxx.js'] {
errno: -2.code: 'ENOENT'.syscall: 'unlink'.path: '/xxxxxx/xxxxxx.js'
}
Copy the code
Fs. mkdir Creates a directory
> fs.mkdir(path.join(process.env.HOME, 'fs'), err= > console.log('err', err))
> err null
Copy the code
If the directory already exists, an error is reported
> fs.mkdir('/usr'.err= > console.log('err', err))
> err [Error: EEXIST: file already exists, mkdir '/usr'] {
errno: -17.code: 'EEXIST'.syscall: 'mkdir'.path: '/usr'
}
Copy the code
Fs.rmdir Deletes a directory
> fs.rmdir(path.join(process.env.HOME, 'fs'), err= > console.log('err', err))
> err null
Copy the code
An error condition
This operation is dangerous and error reporting is complex.
Directory does not exist
> fs.rmdir('/xxxxxx'.err= > console.log('err', err))
> err [Error: ENOENT: no such file or directory, rmdir '/xxxxxx'] {
errno: -2.code: 'ENOENT'.syscall: 'rmdir'.path: '/xxxxxx'
}
Copy the code
Insufficient permissions
> fs.rmdir('/usr'.err= > console.log('err', err))
> err [Error: EPERM: operation not permitted, rmdir '/usr'] {
errno: -1.code: 'EPERM'.syscall: 'rmdir'.path: '/usr'
}
Copy the code
Directory is not empty
> fs.rmdir(path.join(process.env.HOME, 'testnpm'), err= > console.log('err', err))
> err [Error: ENOTEMPTY: directory not empty, rmdir '/Users/js/testnpm'] {
errno: -66.code: '{ recursive: true }'.syscall: 'rmdir'.path: '/Users/js/testnpm'
}
Copy the code
In a higher versionnode
,fs.rmdir
You can use{ recursive: true }
Parameter item, recursively delete the entire directory, avoidENOTEMPTY
Error. However, some students reported that Node12 did not support it. I have not made a detailed study on this issue. Consider compatibility, or manual recursion, delete as well.
Fs. readdir Reads the list of files in the directory
> fs.readdir('/usr'.(err, res) = > console.log(res))
> [
'X11'.'X11R6'.'bin'.'lib'.'libexec'.'local'.'sbin'.'share'.'standalone'
]
Copy the code
Fs + path recursively reads all files
const path = require('path')
const fs = require('fs')
const read = p= > {
p = path.resolve(process.env.PWD, p)
const exists = fs.existsSync(p)
if(! exists) {return[]}const stat = fs.statSync(p)
if(stat.isFile()) {
return [p]
} else {
return fs.readdirSync(p)
.filter(f= > !/ ^ \. /.test(f))
.map(pp= > path.join(p, pp))
.map(p= > read(p))
.reduce((r, v) = > [...r, ...v], [])
}
}
console.log(read('/').map(f= > f.replace(process.env.HOME, ' ')))
Copy the code
Skills:
- use
path.resolve
+process.env.PWD
The implementation starts from the script run point and completes the completion directory. - use
fs.exists
fs.stat
Determine the existence and type of paths and return different data. - In the use of
path.readdir
After obtaining the file name list, filter it out through the re.
.
Two classes of operand pathing characters. This example will also filter out.
The initial named path is as follows.gitignore
File. - Use recursion to reduce code
- use
reduce
Flatten the array.