readFileSync与使用async/await在readFile之上使用promisify之间的区别 [英] Difference between readFileSync and using promisify on top of readFile with async/await

查看:62
本文介绍了readFileSync与使用async/await在readFile之上使用promisify之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

出于好奇,我想知道两者之间是否有任何区别.

Out of curiosity, i want to know if there is any difference between the two.

readFileSync:

readFileSync:

function parseFile(filePath) {
  let data = fs.readFileSync(filePath);
}

readFile带有承诺:

readFile with promisify:

const readFilePromise = promisify(fs.readFile);
async function parseFile(filePath) {
  let data = await readFilePromise(filePath);
}

如果需要一些上下文,请尝试读取文件夹中的一堆文件,在每个文件夹中替换许多值,然后重新写入.

If you need some context, im trying to read a bunch of files in a folder, replace a lot of values in each one, and write it again.

我不知道使用异步或同步代码执行这些操作是否有任何区别.

I don`t know if there is any difference in using Asyncronous or Synchronous code for these actions.

完整代码:

function parseFile(filePath) {
  let data = fs.readFileSync(filePath);
  let originalData = data.toString();
  let newData = replaceAll(originalData);

  return fs.writeFileSync(filePath, newData);
}

function readFiles(dirPath) {
  let dir = path.join(__dirname, dirPath);
  let files = fs.readdirSync(dir); // gives all the files
  files.map(file => parseFile(path.join(dir, file)));
}

function replaceAll(text) {
  text = text.replace(/a/g, 'b');
  return text;
}

readFiles('/files');

推荐答案

异步和同步代码之间有很大的区别.这种差异是否重要取决于您要尝试执行的操作.您的javascript是单线程线程,因此,当您与 fs.readFileSync 同步读取潜在的大文件时,您将无法执行其他任何操作,例如响应传入的请求.

There's a big difference between the async and synchronous code. Whether that difference matters depends on what you are trying to do. Your javascript is singe threaded, so while you are reading a potentially large file synchronously with fs.readFileSync you can't do anything else such as respond to incoming requests.

如果您正在运行繁忙的服务器,则可能会导致严重问题,因为在读取文件时请求排队,并且您可能永远无法追上.

If you are running a busy server this can cause big problems because requests queue up while you are reading the file and you may never catch up.

使用async方法,文件读取发生在代码之外,并且在完成后会回叫代码.在执行此操作时,您的代码可以自由地响应其他请求.

With the async method the file read happens outside your code and it calls your code back when it's done. While it's doing this your code is free to respond to other requests.

如果您只是尝试读取本地文件,并且线程是否阻塞都没有关系,则可以使用其中任何一个.

If you are just trying to read a local file and it doesn't matter if the thread blocks, then you can use either.

这篇关于readFileSync与使用async/await在readFile之上使用promisify之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆