Node.js uses threads from worker pool to perform I/O operations. If I need to count the number of characters in many files concurrently (using Promise.all), is it safe to update the totalNumberOfChars variable which is common to all promisifed file read operations? Because a separate thread may be used for each read operation can totalNumberOfChars be incorrect?
This is the code:
const fs = require("fs");
const util = require("util");
const readFileAsync = util.promisify(fs.readFile);
/**
*
* @param {Array} pathsToFiles - array of paths to files
*/
const main = async (pathsToFiles) => {
let totalNumberOfChars = 0;
await Promise.all(
pathsToFiles.map(async (path) => {
const chars = await readFileAsync(path);
totalNumberOfChars += chars.length;
})
);
console.log("totalNumberOfChars", totalNumberOfChars);
};
main(['/home/a.txt', '/home/b.txt'])
This is safe, because what's inside this function:
pathsToFiles.map(async (path) => {
const chars = await readFileAsync(path);
totalNumberOfChars += chars.length;
})
is executed synchronously, meaning that your file is read synchronously (again, inside that callback!) and you're adding to counter synchronously as well. So after the "main" function's execution you'll receive the right answer.