教程 > nodejs 教程 > 阅读:507

node.js 文件中查找字符串——迹忆客-ag捕鱼王app官网

在 node.js 中检查文件是否包含字符串:

  1. 使用 fs.readfilesync() 方法读取文件。
  2. 使用 includes() 方法检查字符串是否包含在文件中。
  3. 如果字符串包含在文件中,includes 方法将返回 true。
// 如果使用 es6 导入将以下注释打开
// import {readfilesync, promises as fspromises} from 'fs';
const {readfilesync, promises: fspromises} = require('fs');
// 同步读取文件
function checkifcontainssync(filename, str) {
  const contents = readfilesync(filename, 'utf-8');
  const result = contents.includes(str);
  return result;
}
//  true
console.log(checkifcontainssync('./example.txt', 'hello'));
// --------------------------------------------------------------
// 异步读取文件
async function checkifcontainsasync(filename, str) {
  try {
    const contents = await fspromises.readfile(filename, 'utf-8');
    const result = contents.includes(str);
    console.log(result);
    return result;
  } catch (err) {
    console.log(err);
  }
}
// promise
checkifcontainsasync('./example.txt', 'hello');

第一个示例中的函数同步读取文件的内容。

fs.readfilesync 方法将文件的路径作为第一个参数,将编码作为第二个参数。

该方法返回所提供路径的内容。

如果省略 encoding 参数,该函数将返回一个缓冲区,否则返回一个字符串。

我们使用 string.includes 方法来检查文件的内容是否包含提供的字符串。

include 方法执行区分大小写的搜索,以检查提供的字符串是否在另一个字符串中找到。

如果我们需要进行不区分大小写的搜索,请将文件的内容和传入的字符串转换为小写。

// 如果使用 es6 导入将以下注释打开
// import {readfilesync, promises as fspromises} from 'fs';
const {readfilesync, promises: fspromises} = require('fs');
//  同步读取文件
function checkifcontainssync(filename, str) {
  const contents = readfilesync(filename, 'utf-8');
  // 将两者都转换为小写以进行不区分大小写的检查
  const result = contents.tolowercase().includes(str.tolowercase());
  return result;
}
// true
console.log(checkifcontainssync('./example.txt', 'hello'));

上面的代码片段假设有一个 example.txt 文件位于同一目录中。 确保也在同一目录中打开我们的终端。

hello world
one
two
three

示例中的目录结构假设 index.js 文件和 example.txt 文件位于同一文件夹中,并且我们的终端也在该文件夹中。

或者,我们可以使用 fspromises 对象异步读取文件。

在 node.js 中检查文件是否包含字符串:

  1. 使用 fspromises.readfile() 方法读取文件。
  2. 使用 includes() 方法检查字符串是否包含在文件中。
  3. 如果字符串包含在文件中,includes 方法将返回 true。
// 如果使用 es6 导入将以下注释打开
// import {readfilesync, promises as fspromises} from 'fs';
const {readfilesync, promises: fspromises} = require('fs');
// 异步读取文件
async function checkifcontainsasync(filename, str) {
  try {
    const contents = await fspromises.readfile(filename, 'utf-8');
    const result = contents.includes(str);
    console.log(result);
    return result;
  } catch (err) {
    console.log(err);
  }
}
checkifcontainsasync('./example.txt', 'hello');

fspromises.readfile() 方法异步读取所提供文件的内容。

如果我们没有为 encoding 参数提供值,则该方法返回一个缓冲区,否则返回一个字符串。

该方法返回一个满足文件内容的promise,因此我们必须等待它或对其使用 .then() 方法来获取已解析的字符串。

请注意,checkifcontainsasync 函数返回一个用布尔值解析的 promise。

它不像第一个代码片段中的同步方法那样直接返回布尔值。

查看笔记

扫码一下
查看教程更方便
网站地图