21xrx.com
2024-09-20 05:47:09 Friday
登录
文章检索 我的文章 写文章
Node.js 实现多行输入输出处理
2023-06-22 02:33:46 深夜i     --     --
Node js 多行输入 输出处理

Node.js 是一种基于 Chrome V8 引擎的 JavaScript 运行环境,可用于服务器端编程。它具有轻量、高效、可扩展等特点,适用于处理大量的输入输出。

在 Node.js 中实现多行输入输出处理是很常见的操作,主要有以下几种方法:

1.使用 readline 模块

readline 模块是 Node.js 内置模块之一,它提供了一个接口,用于逐行读取数据流。我们可以使用该模块来实现多行输入输出的处理。

下面是一个例子,通过 readline 模块读取控制台输入的多行文本,并将每行文本首字母变成大写后输出:


const readline = require('readline');

const rl = readline.createInterface(

 input: process.stdin);

let count = 0;

let result = '';

rl.on('line', function (input) {

 if (count === 0) {

  count = parseInt(input);

 } else {

  result += input.charAt(0).toUpperCase() + input.slice(1) + '\n';

  count--;

 }

 if (count === 0) {

  console.log(result.trim());

  rl.close();

 }

});

2.使用 fs 模块

fs 模块是 Node.js 内置模块之一,它提供了文件系统相关的 API,包括读写文件、创建目录、删除文件等操作。我们可以使用该模块来处理读取和写入多行文本数据。

下面是一个例子,通过 fs 模块读取本地文件的多行文本数据,并将每行文本首字母变成大写后写入到新的文件中:


const fs = require('fs');

const path = './input.txt';

fs.readFile(path, 'utf8', function (err, data) {

 if (err) throw err;

 

 const lines = data.split('\n').map(line =>

  line.charAt(0).toUpperCase() + line.slice(1)

 );

 

 const output = lines.join('\n');

 const outputPath = './output.txt';

 

 fs.writeFile(outputPath, output, function (err) {

  if (err) throw err;

  console.log('The file has been saved!');

 });

});

3.使用 Promise

Promise 是一种用于异步编程的解决方案,它可以更高效地处理多个异步操作。我们可以使用 Promise 来实现多行输入输出处理,简化代码的实现。

下面是一个例子,通过 Promise 封装 readline 模块实现读取控制台输入的多行文本,并将每行文本首字母变成大写后输出:


const readline = require('readline');

function readLines() {

 const rl = readline.createInterface(

  input: process.stdin

 );

 

 return new Promise((resolve, reject) => {

  const lines = [];

  

  rl.on('line', line => {

   lines.push(line.charAt(0).toUpperCase() + line.slice(1));

  });

  

  rl.on('close', () => {

   resolve(lines);

  });

 });

}

(async () => {

 const lines = await readLines();

 console.log(lines.join('\n'));

})();

总之,Node.js 的多行输入输出处理涉及到了 readline 模块、fs 模块和 Promise 等操作,我们可以根据实际需求选择其中一种或多种实现方式,以提高代码的效率和可读性。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复