一座被设计为能避开气流的建筑 (https://pixelz.cc)
软件应用程序在计算机的主存储器中运行, 我们称之为随机存取存储器 (RAM).JavaScript, 尤其是 Node.JS (服务端 JS) 允许我们为终端用户编写从小型到大型的软件项目. 处理程序的内存总是一个棘手的问题, 因为糟糕的实现可能会阻塞在给定服务器或系统上运行的所有其他应用程序. C 和 C++ 程序员确实关心内存管理, 因为隐藏在代码的每个角落都有可能出现可怕的内存泄漏. 但是对于 JS 开发者来说, 你真的有关心过这个问题吗?
由于 JS 开发人员通常在专用的高容量服务器上进行 web 服务器编程, 他们可能不会察觉多任务处理的延迟. 比方说在开发 Web 服务器的情况下, 我们也会运行多个应用程序, 如数据库服务器 ( MySQL ), 缓存服务器( Redis ) 和其他需要的应用. 我们需要知道它们也会消耗可用的主内存. 如果我们随意地编写应用程序, 很可能会降低其他进程的性能, 甚至让内存完全拒绝对它们的分配. 在本文中, 我们通过解决一个问题来了解 Node.JS 的流, 缓冲区和管道等结构, 并了解它们分别如何支持编写内存有效的应用程序.
我们使用 Node.JS v8.12.0 来运行这些程序, 所有代码示例都放在这里:
- const fs = require('fs');
- let fileName = process.argv[2];
- let destPath = process.argv[3];
- fs.readFile(fileName, (err, data) => {
- if (err) throw err;
- fs.writeFile(destPath || 'output', data, (err) => {
- if (err) throw err;
- });
- console.log('New file has been created!');
- });
- /home/shobarani/Workspace/basic_copy.JS:7
- if (err) throw err;
- ^
- RangeError: File size is greater than possible Buffer: 0x7fffffff bytes
- at FSReqWrap.readFileAfterStat [as oncomplete] (fs.JS:453:11)
- let buffer = new Buffer(10); # 10 为 buffer 的体积
- console.log(buffer); # prints
- let buffer = new Buffer.alloc(10);
- console.log(buffer); # prints
- let name = 'Node JS DEV';
- let buffer = Buffer.from(name);
- console.log(buffer) # prints
- /*
- A file copy with streams and events - Author: Naren Arya
- */
- const stream = require('stream');
- const fs = require('fs');
- let fileName = process.argv[2];
- let destPath = process.argv[3];
- const readabale = fs.createReadStream(fileName);
- const writeable = fs.createWriteStream(destPath || "output");
- fs.stat(fileName, (err, stats) => {
- this.fileSize = stats.size;
- this.counter = 1;
- this.fileArray = fileName.split('.');
- try {
- this.duplicate = destPath + "/" + this.fileArray[0] + '_Copy.' + this.fileArray[1];
- } catch(e) {
- console.exception('File name is invalid! please pass the proper one');
- }
- process.stdout.write(`File: ${this.duplicate} is being created:`);
- readabale.on('data', (chunk)=> {
- let percentageCopied = ((chunk.length * this.counter) / this.fileSize) * 100;
- process.stdout.clearLine(); // clear current text
- process.stdout.cursorTo(0);
- process.stdout.write(`${Math.round(percentageCopied)}%`);
- writeable.write(chunk);
- this.counter += 1;
- });
- readabale.on('end', (e) => {
- process.stdout.clearLine(); // clear current text
- process.stdout.cursorTo(0);
- process.stdout.write("Successfully finished the operation");
- return;
- });
- readabale.on('error', (e) => {
- console.log("Some error occured:", e);
- });
- writeable.on('finish', () => {
- console.log("Successfully created the file copy!");
- });
- });
- Disk Read: 53.4 MiB/s
- Disk Write: 14.8 MiB/s
- /*
- A file copy with streams and piping - Author: Naren Arya
- */
- const stream = require('stream');
- const fs = require('fs');
- let fileName = process.argv[2];
- let destPath = process.argv[3];
- const readabale = fs.createReadStream(fileName);
- const writeable = fs.createWriteStream(destPath || "output");
- fs.stat(fileName, (err, stats) => {
- this.fileSize = stats.size;
- this.counter = 1;
- this.fileArray = fileName.split('.');
- try {
- this.duplicate = destPath + "/" + this.fileArray[0] + '_Copy.' + this.fileArray[1];
- } catch(e) {
- console.exception('File name is invalid! please pass the proper one');
- }
- process.stdout.write(`File: ${this.duplicate} is being created:`);
- readabale.on('data', (chunk) => {
- let percentageCopied = ((chunk.length * this.counter) / this.fileSize) * 100;
- process.stdout.clearLine(); // clear current text
- process.stdout.cursorTo(0);
- process.stdout.write(`${Math.round(percentageCopied)}%`);
- this.counter += 1;
- });
- readabale.pipe(writeable); // Auto pilot ON!
- // In case if we have an interruption while copying
- writeable.on('unpipe', (e) => {
- process.stdout.write("Copy has failed!");
- });
- });
- Disk Read: 35.5 MiB/s
- Disk Write: 35.5 MiB/s
- const readabale = fs.createReadStream(fileName);
- readable.read(no_of_bytes_size);
来源: http://developer.51cto.com/art/202001/609436.htm