Reputation: 546
I'm currently doing a Node.JS course where we are working on reading, writing, saving and editing the user's input data through the terminal using fs.writeFileSync(). It works fine for text which is a few sentences long, but anything larger and instead of running the code, the node terminal (>) starts to run.
I have a basic understanding of node.js, but can't figure out why this keeps happening. Any help is really appreciated. Thanks.
Code below,
const fs = require('fs');
var originalNote = {
title: process.argv[2],
body: process.argv[3],
};
var originalNoteString = JSON.stringify(originalNote);
fs.writeFileSync('Notes.json', originalNoteString);
var noteString = fs.readFileSync('Notes.json');
var Note = JSON.parse(noteString);
console.log(typeof (Note));
console.log(originalNoteString);
console.log(Note.title);
Viveks-MacBook-Pro:playground Vivek$ node JSON.js 'Lorem Ipsum' 'ldfdfefnhebfhbfhrbfherbfhrbfhrefocalStorage fefef fede'
object
{"title":"Lorem Ipsum","body":"ldfdfefnhebfhbfhrbfherbfhrbfhrefocalStorage fefef fede"}
Viveks-MacBook-Pro:playground Vivek$ node JSON.js 'Lorem Ipsum' 'Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a typespecimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum'
'>'
Upvotes: 1
Views: 1148
Reputation: 3976
The basic problem is in the data sent in second argument.
If you look at the data, it has the word industry's
which involves single quote
in it.
this is causing the second argument to get truncated.
If you put the second argument in a double quote, your code should work fine.
You can also use escape characters if possible to ignore the single quotes in the data.
I hope this helps :)
Upvotes: 0
Reputation: 1
Call "notes.json" directly using require rather than reading it as a file.
var noteString = require('Notes.json');
If your json is properly formed, you can directly work with it. If you insist on calling the file via readFileSync, use 'utf-8' as an additional parameter.
var noteString = fs.readFileSync('Notes.json','utf-8');
Hope this helps!
Upvotes: -1