http module and fs module

Article link: http module and fs module

http module

responseObject common methods:

  1. response.writeHead(200,{'Content-Type':'text/plain:charset=UTF-8'});

This method can only be called once on a message and must be calledresponse.end()Before calling.

  1. response.write()Send a corresponding body to send the corresponding data to the client.writeIt can be used many times, but it must be used in the endendTo end the response, otherwise the client will wait.
  2. response.end()This method signals the server that all response headers and principals have been sent and that the server should be considered complete for this message. Method must be called on each responseresponse.end().
const http = require('http');
http.createServer(function(req, res) {
  res.writeHead(200, {'Content-Type': 'text/html'});
  res.write('hello world');
  res.write('<h1>hello node.js</h1>');
  res.end();
}).listen(8080);
console.log('Server running at http://127.0.0.1:8080');

request object

  1. request.url gets the request path, which is the part of the path after the port number. That is to say, all URLs start with / to judge the path processing response.
  2. request.socket.localAddress gets the ip address.
  3. request.socket.remotePort gets the source port.
const http = require('http');

let server = http.createServer();
server.on('request', function(req, res) {
  console.log('Received the request. The request path is:' + req.url);
  console.log('The address of the client requesting me is:', req.socket.remoteAddress, req.socket.remotePort);
  let url = req.url;
  res.writeHead(200, {'Content-Type': 'text/html;charset=UTF-8'});
  switch (url) {
    case '/':
      res.end('<h1>Index page</h1>');
      break;
    case '/login':
      res.end('<h1>Login page</h1>');
      break;
    default:
      res.end('404 Not Found.');
      break;
  }
});
server.listen(8080, function() {
  console.log('The server is started successfully and can be accessed...');
});

fs module

All file system operations take the form of synchronous and asynchronous. The first parameter of a callback in an asynchronous method is always reserved for the exception parameter. If the method completes successfully, the parameter is null or undefined.

Because Node.js is a single thread, most of the code in Node.js needs to execute business logic repeatedly during the server running period. Asynchronous code must be used, otherwise, the server will stop responding when the synchronous code is executing.

When the server needs to read the configuration file at startup or write to the state file at the end, you can use synchronization code, because these codes are only executed once at startup and end, and do not affect the asynchronous execution of the server during normal operation.

Open file

Syntax format of asynchronous open file: fs.open(path,flags[mode],callback);

Parameter Description:

  • Path: file path.
  • flags: the behavior of opening a file.
  • Mode: set the file mode (permission). The default permission for file creation is 0o666 (read-write).
  • Callback: a callback function with two parameters: callback(err,fd).

flagsParameters:

  • a - Open the file for appending. If the file does not exist, it is created.
  • ax - And a Similar, but fails if the path exists.
  • a+ - Open files for reading and appending. If the file does not exist, it is created.
  • ax+ - And a+ Similar, but fails if the path exists.
  • as - Open the file in synchronous mode for appending. If the file does not exist, it is created.
  • as+ - Open the file in synchronous mode for reading and appending. If the file does not exist, it is created.
  • r - Open the file for reading. If the file does not exist, an exception occurs.
  • r+ - Open files for reading and writing. If the file does not exist, an exception occurs.
  • rs+ - Open the file in synchronous mode for reading and writing. Instructs the operating system to bypass the local file system cache. This is for NFS It's useful to mount open files because it allows you to skip potentially stale local caches It's right. I/O Performance has a very real impact, so this flag is not recommended unless required. This is not going to happen. fs.open() or fsPromises.open() Block call converted to synchronous If synchronous operation is required, use the fs.openSync() And so on.
  • w - Open the file for writing. Create a file if it doesn't exist or truncate it if it exists.
  • wx - And w Similar, but fails if the path exists.
  • w+ - Open files for reading and writing. Create a file if it doesn't exist or truncate it if it exists.
  • wx+ - And w+ Similar, but fails if the path exists.
const fs = require('fs');

fs.open('file/syl.txt', 'r+', function(err, fd) {
  if (err) {
    return console.error(err);
  }
  console.log('File opened successfully!');
});

Close file

Syntax format of asynchronous open file: fs.close(fs,callback);

const fs = require('fs');

fs.open('file/syl.txt', 'r+', function(err, fd) {
  if (err) {
    return console.error(err);
  }
  console.log('File opened successfully!');
  fs.close(fd, function(err) {
    if (err) {
      console.log(err);
    }
    console.log('File closed successfully');
  });
});

Using fs.read and fs.write to read and write files

Using fs.read and fs.write to read and write files requires fs.open to open files and fs.close to close files.

Reading files with fs.read

Syntax format of asynchronous read file: fs.read(fs,buffer,offset,length,position,callback)

Parameters:

  • fd: the file descriptor returned through the fs.open() method.
  • Buffer: buffer for data writing.
  • Offset: the offset in the buffer to start writing.
  • length: an integer that specifies the number of bytes to read.
  • Position: specifies where to start reading from the file. If the position is null, the data is read from the current file location and the file location is updated.
  • Callback: a callback function with three parameters err, bytesRead and buffer.
const fs = require('fs');

fs.open('file/syl.txt', 'r+', function(err, fd) {
  if (err) {
    return console.error(err);
  }
  console.log('File opened successfully!');
  console.log('Ready to read file:');
  // Create a cache size of 1024 bytes
  let buf = Buffer.alloc(1024);
  // Asynchronous read file
  fs.read(fd, buf, 0, buf.length, 0, function(err, bytes, buf) {
    if (err) {
      console.log(err);
    }
    console.log(bytes + 'Bytes read');
    if (bytes > 0) {
      console.log(buf.slice(0, bytes).toString());
    }
    fs.close(fd, function(err) {
      if (err) {
        console.log(err);
      }
      console.log('File closed successfully');
    });
  });
});
// File opened successfully!
// Ready to read file:
// 5 bytes read
// Hello
// File closed successfully

Write file using fs.write

Syntax format of asynchronous write file: fs.write(fd,buffer,offset,length,position,callback);

const fs = require('fs');

fs.open('file/syl.txt', 'a', function(err, fd) {
  if (err) {
    return console.error(err);
  }
  console.log('File opened successfully!');
  console.log('Prepare to write to file:');
  let buf = Buffer.from(new String('Hello World'));
  fs.write(fd, buf, 0, 11, 0, function(err, bytes, buf) {
    if (err) {
      console.log(err);
    }
    console.log('Write successfully');
    console.log(bytes + 'Bytes written');
    console.log(buf.slice(0, bytes).toString());
    fs.close(fd, function(err) {
      if (err) {
        console.log(err);
      }
      console.log('File closed successfully');
    });
  });
});
// File opened successfully!
// Prepare to write to file:
// Write successfully
// 11 bytes written
// Hello World
// File closed successfully

Another syntax: fs.write(fd,string,position,encoding,callback);

const fs = require('fs');

fs.open('file/syl.txt', 'a', function(err, fd) {
  if (err) {
    return console.error(err);
  }
  console.log('File opened successfully!');
  console.log('Prepare to write to file:');
  let data = ',Hello Node.js';
  fs.write(fd, data, 0, 'utf-8', function(err, bytes, buffer) {
    if (err) {
      console.log(err);
    }
    console.log(bytes + 'Bytes written');
    console.log(buffer);
    fs.close(fd, function(err) {
      if (err) {
        console.log(err);
      }
      console.log('File closed successfully');
    });
  });
});
// File opened successfully!
// Prepare to write to file:
// 14 bytes written
// ,Hello Node.js
// File closed successfully

fs.read and fs.write need to be combined with fs.open to get the file handle.

readFile read file

Syntax format: fs.readFile(path,[options],callback);

Parameters:

  • path: filename or file descriptor.
  • options: this parameter is an object containing {encoding,flag}. The encoding default value is null, and the flag default value is r.

The first way:

const fs = require('fs');

fs.readFile('file/syl.txt', 'utf-8', function(err, data) {
  if (err) {
    throw  err;
  }
  console.log(data);
});

The second way:

fs.readFile('file/syl.txt', function(err, data) {
  if (err) {
    throw  err;
  }
  console.log(data.toString());
});

writeFile write file

Syntax format: fs.writeFile(file,data,[options],callback);

const fs = require('fs');

fs.writeFile('file/syl.txt', 'I'm new', function(err) {
  if (err) {
    throw  err;
  }
  console.log('Have been saved');
  fs.readFile('file/syl.txt', 'utf-8', function(err, data) {
    if (err) {
      throw err;
    }
    console.log(data);
  });
});
// Have been saved
// I'm new

We can change the default write mode by setting the value of flag, for example, setting a to append data to a file.

fs.writeFile('file/syl.txt', 'I'm new', {'flag': 'a'}, function(err) {
  if (err) {
    throw  err;
  }
  console.log('Have been saved');
  fs.readFile('file/syl.txt', 'utf-8', function(err, data) {
    if (err) {
      throw err;
    }
    console.log(data);
  });
});

Get file information

Syntax format: fs.stat(path,callback);

It is not recommended to use fs.stat() to check the existence of a file before calling fs.open(), fs.readFile(), or fs.writeFile(). Instead, you should open, read, or write to the file directly, and handle the errors raised when the file is not available.

fs.stat(path)After execution, thestatsAn instance of class is returned to its callback function. Can passstatsClass to determine the properties of the file.

const fs = require('fs');

fs.stat('file/syl.txt', function(err, stats) {
  console.log(stats.isFile());
});
// true

Intercepting files

Syntax format: fs.ftruncate(fd,len,callback);

const fs = require('fs');

fs.open('file/syl.txt', 'r+', function(err, fd) {
  if (err) {
    return console.error(err);
  }
  console.log('File opened successfully');
  console.log('Intercept the contents of the file within 6 bytes, and the excess part will be removed.');
  // Intercepting files
  let buf = Buffer.alloc(1024);
  fs.ftruncate(fd, 6, function(err) {
    if (err) {
      console.log(err);
    }
    console.log('The file was intercepted successfully.');
    console.log('Read the same file');
    fs.read(fd, buf, 0, buf.length, 0, function(err, bytes) {
      if (err) {
        console.log(err);
      }
      if (bytes > 0) {
        console.log(buf.slice(0, bytes).toString());
      }

      fs.close(fd, function(err) {
        if (err) {
          console.log(err);
        }
        console.log('File closed successfully!');
      });
    });
  });
});

Delete files

fs.unlink('file/syl.txt', function(err) {
  if (err) {
    return console.error(err);
  }
  console.log('File deleted successfully!');
});

Modify file name

Syntax format: fs.rename(oldPath,newPath,callback);

fs.rename('file/old.txt', 'file/new.txt', err => {
  if (err) throw err;
  console.log('Rename complete');
});

Directory operation

new directory

Syntax format: fs.mkdir(path,callback);

fs.mkdir('./test/', function(err) {
  if (err) {
    return console.error(err);
  }
  console.log('Directory created successfully.');
});

Read directory

Syntax format: fs.readdir(path,callback);

fs.readdir('./test', function(err, files) {
  if (err) {
    throw err;
  }
  console.log(files);
});

Delete directory

Syntax format: fs.rmdir(path,callback);

Only empty directories can be deleted.

fs.rmdir('./test', function(err) {
  if (err) {
    return console.error(err);
  }
});    

Keywords: node.js socket encoding

Added by nrsh_ram on Fri, 01 Nov 2019 21:44:00 +0200