Вы можете создать обещание и использовать async / await для его достижения.
Предположим, у вас есть такая файловая структура:
В account.json у вас есть это:
[
{
"id": 1,
"username": "test1",
"password": "test1"
},
{
"id": 2,
"username": "test2",
"password": "test2"
},
{
"id": 3,
"username": "test3",
"password": "test3"
}
]
Ваш файл index.js должен быть:
// importing required modules
const fs = require('fs');
const path = require('path');
// building the file path location
const filePath = path.resolve(__dirname, 'accounts.json');
// creating a new function to use async / await syntax
const readFile = async () => {
const fileContent = await new Promise((resolve, reject) => {
return fs.readFile(filePath, { encoding: 'utf8' }, (err, data) => {
if (err) {
return reject(err);
}
return resolve(data);
});
});
// printing the file content
console.log(fileContent);
}
// calling the async function to get started with reading file etc.
readFile();