+
95
-

nodejs运行环境如何限制特定函数的执行?比如fs

请问nodejs运行环境如何限制特定函数的执行?比如fs

网友回复

+
15
-

在 Node.js 中,你可以通过多种方法限制特定函数的执行,例如 fs 模块。以下几种常见的方式:

1. 使用 JavaScript 代码控制访问:

封装 fs 模块: 创建一个包装函数,根据你的规则判断是否允许执行 fs 操作。

const fs = require('fs');

function restrictedFs(funcName, ...args) {
  // 添加你的逻辑判断是否允许执行
  if (funcName === 'readFile' && args[0] === 'allowed.txt') {
    return fs[funcName](...args);
  } else {
    console.error('不允许的操作!');
    // 可以选择抛出错误,或者返回默认值
    // throw new Error('不允许的操作!');
    return null;
  }
}

// 使用 restrictedFs 代替 fs
restrictedFs('readFile', 'allowed.txt', 'utf-8', (err, data) => {
  if (err) throw err;
  console.log(data);
});

点击查看剩余70%

我知道答案,我要回答