node js : why can't I write asynchronously in jason.js and then read it synchronously?












-1















Please can anyone help me with this?
my question is: why can't I write asynchronously in jason.js and then read it synchronously?



To make my question clear, here is my code:



const fs = require('fs');

var originalNote = {
title: 'todo list',
body : `that's my secret`
};

var stringNote = JSON.stringify(originalNote);

//here I write asynchronously into my note.json file
fs.writeFile('note.json',stringNote, () => {
console.log('hey there');
});

//here I read synchronously from the note.json file
var file = fs.readFileSync('./note.json');
var note = JSON.parse(file);


when I do this I get the following error:



SyntaxError: Unexpected end of JSON input

at JSON.parse (<anonymous>)

at Object.<anonymous> (/Users/yosra/Desktop/notes-node/playground/json.js:31:18)

at Module._compile (internal/modules/cjs/loader.js:721:30)

at Object.Module._extensions..js (internal/modules/cjs/loader.js:732:10)

at Module.load (internal/modules/cjs/loader.js:620:32)

at tryModuleLoad (internal/modules/cjs/loader.js:560:12)

at Function.Module._load (internal/modules/cjs/loader.js:552:3)

at Function.Module.runMain (internal/modules/cjs/loader.js:774:12)

at executeUserCode (internal/bootstrap/node.js:342:17)

at startExecution (internal/bootstrap/node.js:276:5)


but when I make everything synchronous it works.



Thanks a lot










share|improve this question







New contributor




Yosra is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
















  • 1





    Are you sure you understand what "asynchronously" means? The .writeFile() function call returns immediately, before the file has actually been written.

    – Pointy
    Jan 18 at 14:22











  • @Pointy yes, synchronous code is executed in a linear way which is not the case for asynchonous code.

    – Yosra
    Jan 18 at 14:47











  • nodejs.org/dist/latest-v11.x/docs/api/… I may be wrong, but here they say that it doesn't return immediatly

    – Yosra
    Jan 18 at 14:49











  • "Asynchronously writes data to a file" — that means it returns immediately. The callback is invoked when the operation completes.

    – Pointy
    Jan 18 at 14:52











  • ooh yeah, of course thank you so much, I get it now :) .

    – Yosra
    Jan 18 at 15:04
















-1















Please can anyone help me with this?
my question is: why can't I write asynchronously in jason.js and then read it synchronously?



To make my question clear, here is my code:



const fs = require('fs');

var originalNote = {
title: 'todo list',
body : `that's my secret`
};

var stringNote = JSON.stringify(originalNote);

//here I write asynchronously into my note.json file
fs.writeFile('note.json',stringNote, () => {
console.log('hey there');
});

//here I read synchronously from the note.json file
var file = fs.readFileSync('./note.json');
var note = JSON.parse(file);


when I do this I get the following error:



SyntaxError: Unexpected end of JSON input

at JSON.parse (<anonymous>)

at Object.<anonymous> (/Users/yosra/Desktop/notes-node/playground/json.js:31:18)

at Module._compile (internal/modules/cjs/loader.js:721:30)

at Object.Module._extensions..js (internal/modules/cjs/loader.js:732:10)

at Module.load (internal/modules/cjs/loader.js:620:32)

at tryModuleLoad (internal/modules/cjs/loader.js:560:12)

at Function.Module._load (internal/modules/cjs/loader.js:552:3)

at Function.Module.runMain (internal/modules/cjs/loader.js:774:12)

at executeUserCode (internal/bootstrap/node.js:342:17)

at startExecution (internal/bootstrap/node.js:276:5)


but when I make everything synchronous it works.



Thanks a lot










share|improve this question







New contributor




Yosra is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
















  • 1





    Are you sure you understand what "asynchronously" means? The .writeFile() function call returns immediately, before the file has actually been written.

    – Pointy
    Jan 18 at 14:22











  • @Pointy yes, synchronous code is executed in a linear way which is not the case for asynchonous code.

    – Yosra
    Jan 18 at 14:47











  • nodejs.org/dist/latest-v11.x/docs/api/… I may be wrong, but here they say that it doesn't return immediatly

    – Yosra
    Jan 18 at 14:49











  • "Asynchronously writes data to a file" — that means it returns immediately. The callback is invoked when the operation completes.

    – Pointy
    Jan 18 at 14:52











  • ooh yeah, of course thank you so much, I get it now :) .

    – Yosra
    Jan 18 at 15:04














-1












-1








-1


0






Please can anyone help me with this?
my question is: why can't I write asynchronously in jason.js and then read it synchronously?



To make my question clear, here is my code:



const fs = require('fs');

var originalNote = {
title: 'todo list',
body : `that's my secret`
};

var stringNote = JSON.stringify(originalNote);

//here I write asynchronously into my note.json file
fs.writeFile('note.json',stringNote, () => {
console.log('hey there');
});

//here I read synchronously from the note.json file
var file = fs.readFileSync('./note.json');
var note = JSON.parse(file);


when I do this I get the following error:



SyntaxError: Unexpected end of JSON input

at JSON.parse (<anonymous>)

at Object.<anonymous> (/Users/yosra/Desktop/notes-node/playground/json.js:31:18)

at Module._compile (internal/modules/cjs/loader.js:721:30)

at Object.Module._extensions..js (internal/modules/cjs/loader.js:732:10)

at Module.load (internal/modules/cjs/loader.js:620:32)

at tryModuleLoad (internal/modules/cjs/loader.js:560:12)

at Function.Module._load (internal/modules/cjs/loader.js:552:3)

at Function.Module.runMain (internal/modules/cjs/loader.js:774:12)

at executeUserCode (internal/bootstrap/node.js:342:17)

at startExecution (internal/bootstrap/node.js:276:5)


but when I make everything synchronous it works.



Thanks a lot










share|improve this question







New contributor




Yosra is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.












Please can anyone help me with this?
my question is: why can't I write asynchronously in jason.js and then read it synchronously?



To make my question clear, here is my code:



const fs = require('fs');

var originalNote = {
title: 'todo list',
body : `that's my secret`
};

var stringNote = JSON.stringify(originalNote);

//here I write asynchronously into my note.json file
fs.writeFile('note.json',stringNote, () => {
console.log('hey there');
});

//here I read synchronously from the note.json file
var file = fs.readFileSync('./note.json');
var note = JSON.parse(file);


when I do this I get the following error:



SyntaxError: Unexpected end of JSON input

at JSON.parse (<anonymous>)

at Object.<anonymous> (/Users/yosra/Desktop/notes-node/playground/json.js:31:18)

at Module._compile (internal/modules/cjs/loader.js:721:30)

at Object.Module._extensions..js (internal/modules/cjs/loader.js:732:10)

at Module.load (internal/modules/cjs/loader.js:620:32)

at tryModuleLoad (internal/modules/cjs/loader.js:560:12)

at Function.Module._load (internal/modules/cjs/loader.js:552:3)

at Function.Module.runMain (internal/modules/cjs/loader.js:774:12)

at executeUserCode (internal/bootstrap/node.js:342:17)

at startExecution (internal/bootstrap/node.js:276:5)


but when I make everything synchronous it works.



Thanks a lot







javascript node.js asynchronous synchronization






share|improve this question







New contributor




Yosra is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.











share|improve this question







New contributor




Yosra is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









share|improve this question




share|improve this question






New contributor




Yosra is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









asked Jan 18 at 14:19









YosraYosra

31




31




New contributor




Yosra is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.





New contributor





Yosra is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.






Yosra is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.








  • 1





    Are you sure you understand what "asynchronously" means? The .writeFile() function call returns immediately, before the file has actually been written.

    – Pointy
    Jan 18 at 14:22











  • @Pointy yes, synchronous code is executed in a linear way which is not the case for asynchonous code.

    – Yosra
    Jan 18 at 14:47











  • nodejs.org/dist/latest-v11.x/docs/api/… I may be wrong, but here they say that it doesn't return immediatly

    – Yosra
    Jan 18 at 14:49











  • "Asynchronously writes data to a file" — that means it returns immediately. The callback is invoked when the operation completes.

    – Pointy
    Jan 18 at 14:52











  • ooh yeah, of course thank you so much, I get it now :) .

    – Yosra
    Jan 18 at 15:04














  • 1





    Are you sure you understand what "asynchronously" means? The .writeFile() function call returns immediately, before the file has actually been written.

    – Pointy
    Jan 18 at 14:22











  • @Pointy yes, synchronous code is executed in a linear way which is not the case for asynchonous code.

    – Yosra
    Jan 18 at 14:47











  • nodejs.org/dist/latest-v11.x/docs/api/… I may be wrong, but here they say that it doesn't return immediatly

    – Yosra
    Jan 18 at 14:49











  • "Asynchronously writes data to a file" — that means it returns immediately. The callback is invoked when the operation completes.

    – Pointy
    Jan 18 at 14:52











  • ooh yeah, of course thank you so much, I get it now :) .

    – Yosra
    Jan 18 at 15:04








1




1





Are you sure you understand what "asynchronously" means? The .writeFile() function call returns immediately, before the file has actually been written.

– Pointy
Jan 18 at 14:22





Are you sure you understand what "asynchronously" means? The .writeFile() function call returns immediately, before the file has actually been written.

– Pointy
Jan 18 at 14:22













@Pointy yes, synchronous code is executed in a linear way which is not the case for asynchonous code.

– Yosra
Jan 18 at 14:47





@Pointy yes, synchronous code is executed in a linear way which is not the case for asynchonous code.

– Yosra
Jan 18 at 14:47













nodejs.org/dist/latest-v11.x/docs/api/… I may be wrong, but here they say that it doesn't return immediatly

– Yosra
Jan 18 at 14:49





nodejs.org/dist/latest-v11.x/docs/api/… I may be wrong, but here they say that it doesn't return immediatly

– Yosra
Jan 18 at 14:49













"Asynchronously writes data to a file" — that means it returns immediately. The callback is invoked when the operation completes.

– Pointy
Jan 18 at 14:52





"Asynchronously writes data to a file" — that means it returns immediately. The callback is invoked when the operation completes.

– Pointy
Jan 18 at 14:52













ooh yeah, of course thank you so much, I get it now :) .

– Yosra
Jan 18 at 15:04





ooh yeah, of course thank you so much, I get it now :) .

– Yosra
Jan 18 at 15:04












2 Answers
2






active

oldest

votes


















0














Welcome to Stack Overflow!



As for your questions, you are not handling async code correctly. your read should happen AFTER your write, so you should do the below:



const fs = require('fs');

var originalNote = {
title: 'todo list',
body : `that's my secret`
};

var stringNote = JSON.stringify(originalNote);

//here I write asynchronously into my note.json file
fs.writeFile('note.json',stringNote, () => {
console.log('hey there');
//here I read synchronously from the note.json file
var file = fs.readFileSync('./note.json');
var note = JSON.parse(file);
});





share|improve this answer
























  • Thank you so much

    – Yosra
    Jan 18 at 14:45











  • you are welcome. Can you please mark this as the answer so other folks may benefit? or select @Nicks answer from above. seems he and I answered at the same time (just about)

    – LostJon
    17 hours ago





















0














You want to try to read the file after it's written. That means you have to do it in the callback function of writeFile.



//here I write asynchronously into my note.json file
fs.writeFile('note.json',stringNote, () => {
console.log('hey there');
//here I read synchronously from the note.json file
var file = fs.readFileSync('./note.json');
var note = JSON.parse(file);

});





share|improve this answer
























  • Thank you so much I get it now

    – Yosra
    Jan 18 at 14:45











Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});






Yosra is a new contributor. Be nice, and check out our Code of Conduct.










draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54255880%2fnode-js-why-cant-i-write-asynchronously-in-jason-js-and-then-read-it-synchron%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























2 Answers
2






active

oldest

votes








2 Answers
2






active

oldest

votes









active

oldest

votes






active

oldest

votes









0














Welcome to Stack Overflow!



As for your questions, you are not handling async code correctly. your read should happen AFTER your write, so you should do the below:



const fs = require('fs');

var originalNote = {
title: 'todo list',
body : `that's my secret`
};

var stringNote = JSON.stringify(originalNote);

//here I write asynchronously into my note.json file
fs.writeFile('note.json',stringNote, () => {
console.log('hey there');
//here I read synchronously from the note.json file
var file = fs.readFileSync('./note.json');
var note = JSON.parse(file);
});





share|improve this answer
























  • Thank you so much

    – Yosra
    Jan 18 at 14:45











  • you are welcome. Can you please mark this as the answer so other folks may benefit? or select @Nicks answer from above. seems he and I answered at the same time (just about)

    – LostJon
    17 hours ago


















0














Welcome to Stack Overflow!



As for your questions, you are not handling async code correctly. your read should happen AFTER your write, so you should do the below:



const fs = require('fs');

var originalNote = {
title: 'todo list',
body : `that's my secret`
};

var stringNote = JSON.stringify(originalNote);

//here I write asynchronously into my note.json file
fs.writeFile('note.json',stringNote, () => {
console.log('hey there');
//here I read synchronously from the note.json file
var file = fs.readFileSync('./note.json');
var note = JSON.parse(file);
});





share|improve this answer
























  • Thank you so much

    – Yosra
    Jan 18 at 14:45











  • you are welcome. Can you please mark this as the answer so other folks may benefit? or select @Nicks answer from above. seems he and I answered at the same time (just about)

    – LostJon
    17 hours ago
















0












0








0







Welcome to Stack Overflow!



As for your questions, you are not handling async code correctly. your read should happen AFTER your write, so you should do the below:



const fs = require('fs');

var originalNote = {
title: 'todo list',
body : `that's my secret`
};

var stringNote = JSON.stringify(originalNote);

//here I write asynchronously into my note.json file
fs.writeFile('note.json',stringNote, () => {
console.log('hey there');
//here I read synchronously from the note.json file
var file = fs.readFileSync('./note.json');
var note = JSON.parse(file);
});





share|improve this answer













Welcome to Stack Overflow!



As for your questions, you are not handling async code correctly. your read should happen AFTER your write, so you should do the below:



const fs = require('fs');

var originalNote = {
title: 'todo list',
body : `that's my secret`
};

var stringNote = JSON.stringify(originalNote);

//here I write asynchronously into my note.json file
fs.writeFile('note.json',stringNote, () => {
console.log('hey there');
//here I read synchronously from the note.json file
var file = fs.readFileSync('./note.json');
var note = JSON.parse(file);
});






share|improve this answer












share|improve this answer



share|improve this answer










answered Jan 18 at 14:27









LostJonLostJon

738211




738211













  • Thank you so much

    – Yosra
    Jan 18 at 14:45











  • you are welcome. Can you please mark this as the answer so other folks may benefit? or select @Nicks answer from above. seems he and I answered at the same time (just about)

    – LostJon
    17 hours ago





















  • Thank you so much

    – Yosra
    Jan 18 at 14:45











  • you are welcome. Can you please mark this as the answer so other folks may benefit? or select @Nicks answer from above. seems he and I answered at the same time (just about)

    – LostJon
    17 hours ago



















Thank you so much

– Yosra
Jan 18 at 14:45





Thank you so much

– Yosra
Jan 18 at 14:45













you are welcome. Can you please mark this as the answer so other folks may benefit? or select @Nicks answer from above. seems he and I answered at the same time (just about)

– LostJon
17 hours ago







you are welcome. Can you please mark this as the answer so other folks may benefit? or select @Nicks answer from above. seems he and I answered at the same time (just about)

– LostJon
17 hours ago















0














You want to try to read the file after it's written. That means you have to do it in the callback function of writeFile.



//here I write asynchronously into my note.json file
fs.writeFile('note.json',stringNote, () => {
console.log('hey there');
//here I read synchronously from the note.json file
var file = fs.readFileSync('./note.json');
var note = JSON.parse(file);

});





share|improve this answer
























  • Thank you so much I get it now

    – Yosra
    Jan 18 at 14:45
















0














You want to try to read the file after it's written. That means you have to do it in the callback function of writeFile.



//here I write asynchronously into my note.json file
fs.writeFile('note.json',stringNote, () => {
console.log('hey there');
//here I read synchronously from the note.json file
var file = fs.readFileSync('./note.json');
var note = JSON.parse(file);

});





share|improve this answer
























  • Thank you so much I get it now

    – Yosra
    Jan 18 at 14:45














0












0








0







You want to try to read the file after it's written. That means you have to do it in the callback function of writeFile.



//here I write asynchronously into my note.json file
fs.writeFile('note.json',stringNote, () => {
console.log('hey there');
//here I read synchronously from the note.json file
var file = fs.readFileSync('./note.json');
var note = JSON.parse(file);

});





share|improve this answer













You want to try to read the file after it's written. That means you have to do it in the callback function of writeFile.



//here I write asynchronously into my note.json file
fs.writeFile('note.json',stringNote, () => {
console.log('hey there');
//here I read synchronously from the note.json file
var file = fs.readFileSync('./note.json');
var note = JSON.parse(file);

});






share|improve this answer












share|improve this answer



share|improve this answer










answered Jan 18 at 14:26









NickNick

3,1041420




3,1041420













  • Thank you so much I get it now

    – Yosra
    Jan 18 at 14:45



















  • Thank you so much I get it now

    – Yosra
    Jan 18 at 14:45

















Thank you so much I get it now

– Yosra
Jan 18 at 14:45





Thank you so much I get it now

– Yosra
Jan 18 at 14:45










Yosra is a new contributor. Be nice, and check out our Code of Conduct.










draft saved

draft discarded


















Yosra is a new contributor. Be nice, and check out our Code of Conduct.













Yosra is a new contributor. Be nice, and check out our Code of Conduct.












Yosra is a new contributor. Be nice, and check out our Code of Conduct.
















Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54255880%2fnode-js-why-cant-i-write-asynchronously-in-jason-js-and-then-read-it-synchron%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Homophylophilia

Updating UILabel text programmatically using a function

Cloud Functions - OpenCV Videocapture Read method fails for larger files from cloud storage