问题
Out of curiosity, i want to know if there is any difference between the two.
readFileSync:
function parseFile(filePath) {
let data = fs.readFileSync(filePath);
}
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.
Full code:
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');
回答1:
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.
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.
来源:https://stackoverflow.com/questions/53729650/difference-between-readfilesync-and-using-promisify-on-top-of-readfile-with-asyn