Get data from fs.readFile
To elaborate on what @Raynos said, the function you have defined is an asynchronous callback. It doesn't execute right away, rather it executes when the file loading has completed. When you call readFile, control is returned immediately and the next line of code is executed. So when you call console.log, your callback has not yet been invoked, and this content has not yet been set. Welcome to asynchronous programming.
Example approaches
const fs = require('fs');
// First I want to read the file
fs.readFile('./Index.html', function read(err, data) {
if (err) {
throw err;
}
const content = data;
// Invoke the next step here however you like
console.log(content); // Put all of the code here (not the best solution)
processFile(content); // Or put the next step in a function and invoke it
});
function processFile(content) {
console.log(content);
}
Or better yet, as Raynos example shows, wrap your call in a function and pass in your own callbacks. (Apparently this is better practice) I think getting into the habit of wrapping your async calls in function that takes a callback will save you a lot of trouble and messy code.
function doSomething (callback) {
// any async callback invokes callback with response
}
doSomething (function doSomethingAfter(err, result) {
// process the async result
});
how to get the data from fs.readfile callback function
callbacks
functions means what do you want to do when data comes?
which means node will start read file and implement next line, without waiting data to came before implement your console.log
.
You can make it as a function that returns promise
like:
const fs = require('fs');
function getInput() {
return new Promise((resolve, reject) => {
let input = [];
fs.readFile('input.txt',(err,data)=>{
if(err) return reject(err);
var input = data.toString().split(' ');
return resolve(input);
})
});
}
getInput().then(input => console.log(input));
or, you can use async
and await
to wait input, read more about async.
Fs.readFile return undefined
Try the following:
const accounts = () => fs.readFileSync(__dirname + '/accounts.json', { endoding: 'utf8'})
const accRead = JSON.parse(accounts())
/*Logging for visualization*/console.log(accRead)
How to get data from fs.readFile in vuejs3
The only way to make this data available in your Vue app is to use the define
plugin in Webpack:
// vue.config.js
const my_data = require('./path/file.json');
module.exports =
{
chainWebpack: config =>
{
config.plugin('define').tap(args =>
{
args[0]['process.env'].MY_JSON_DATA = JSON.stringify(my_data);
return args;
});
}
}
Then you can access your data as process.env.MY_JSON_DATA
Using fs read file I want to the json data in variable to pass to the nodejs
You try this
const {readFile} = require('fs/promises'); // using fs-promises
const path = require('path');
const file = path.join("/users/", "hello.json");
const dataObj = {}; // object you intend to use
readFile(file, {encoding: 'utf-8'}).then((result) => {
if(!dataObj[result]) {
dataObj[result] = JSON.parse(result);
}
});
console.log(dataObj) // result
The JSON file is read first, the result gotten from the readFile
function is appended to the dataObj
object. Hope it can help you or steer you in the right direction
Return value from externally called fs.Readfile() in node
You're using await and async in sendEmail
but not returning any Promise
(So the sendEmail
function doesn't return anything and this is why you get undefined
).
Nevertheless, on the response you're trying to call .then()
even though you used await
.
So you should:
- return Promise in the
sendEmail
function. - decide how you want to handle it, if you use async-await then dont use
.then()
and just analyze the variable and vice versa. generateEmail()
function should also returnPromise
.
For example:
async function sendEmail() {
return new Promise((resolve, reject) => {
// Check if user exists
fs.readFile('./file.json', (err, data) => {
if(err) {
reject()
}
else {
let users = JSON.parse(data)
let dataToWrite = JSON.stringify(users)
fs.writeFile('./file2.json', dataToWrite, (err) => {
if(err) {
console.error(err)
reject()
}
else {
generateEmail(users)
.then((info) => {
resolve(info)
})
.catch(
console.log('err')
reject()
)
}
})
}
})
})
}
Related Topics
Does React Keep the Order for State Updates
Passing Environment-Dependent Variables in Webpack
What's the Best Way to Convert a Number to a String in JavaScript
How to Add External Js Scripts to Vuejs Components
What Does = +_ Mean in JavaScript
Best Way to Iterate Over an Array Without Blocking the Ui
Are Eval() and New Function() the Same Thing
Defining Methods via Prototype VS Using This in the Constructor - Really a Performance Difference
Variable as the Property Name in a JavaScript Object Literal
Is There Any Non-Eval Way to Create a Function with a Runtime-Determined Name
How to Convert an Array of Objects to Object with Key Value Pairs
How to Automate Shadow Dom Elements Using Selenium
Copy Array Items into Another Array
Nodejs VS Node on Ubuntu 12.04
Jquery How to Bind Onclick Event to Dynamically Added HTML Element