I am trying to build a script which read and write some files. The functions are working fine but I am having trouble making the read/write functions asynchronously. The main problem I have is that I am trying to write a file and then I am trying to import it.
For example: given these two functions, the first one is writing to ./myFile.js and the second function is trying to import the file like this:
var fs = require('fs');
const myFile = require('./myFile')
async function writeMyFile() {
return new Promise((resolve, reject) => {
fs.promises.readFile('./myFile.js', 'utf8').then((file) => {
const replacedData = file + 'newLine'
fs.promises
.writeFile('./myFile.js', replacedData)
.then(() => resolve('Writted'))
.catch(() => reject('Error'));
});
});
}
function importMyFile() {
console.log(myFile) // this is always empty
}
await writeMyFile()
importMyFile()
The thing is that I can see myFile is being written correctly, but I cannot see it in the importMyFile function. When I try these functions separately it works (executing the first one and then the second one)
I tried the following:
- Using the
promisefunctions fromfslibrary:fs.promises.readFile()andfs.promises.writeFile()(example above) - Returning a Promise which resolves when
writeMyFileends. (example above) - Importing the file directly in the
readMyFilefunction like this:
function importMyFile() {
const myFile = require('./myFile')
console.log(myFile) // this is always empty
}
- Without returning new Promise like this:
async function writeMyFile() {
const file = await fs.promises.readFile('./myFile.js', 'utf8')
const replacedData = file + 'newLine'
await fs.promises.writeFile('./myFile.js', replacedData)
}
I also see that in the console, the order of the logs are these:
'Writted'
{} //empty file
Keep in mind that this is a simplified version of my case.
EDIT the file I am trying to write and import looks like this ALWAYS:
module.exports = []
And the it is populated, it looks like this:
const myModule = {
name: 'name',
surname: 'surname'
}
module.exports = [myModule]
I hope someone knows what is going on here. Thanks!