Community Bot 1 1 1 silver badge. Matt Cashatt Matt Cashatt Add a comment. Active Oldest Votes. I think JSON. For the sake of completeness. Their exists a npm called jsonfile. I cant believe it was so difficult to find this simple thing.
It takes milliseconds this way, but if I use require , it chugs. For people finding this answer in and on, Node. Show 6 more comments. For example, suppose you have the following JSON file. Travis Tidwell Travis Tidwell 4, 1 1 gold badge 13 13 silver badges 8 8 bronze badges.
Just so folks know, and if I remember correctly, require in node runs synchronously. Dive in deep here — prasanthv. I'd say this is potentially a security threat. If the json file you're loading contains JS code, would require ing it run that code? If so then you really need to control where your json files are coming from or an attacker could run malicious code on your machine.
This is a sound solution for small DevOps scripts or batch operations. You have to balance human time with performance. Possible duplicate of Get data from fs. Show 1 more comment. Active Oldest Votes. Harm 3 3 silver badges 16 16 bronze badges.
Ryan Weir Ryan Weir 6, 4 4 gold badges 37 37 silver badges 57 57 bronze badges. Add a comment. Zuhair Taha Zuhair Taha 2, 1 1 gold badge 28 28 silver badges 29 29 bronze badges.
Sign up or log in Sign up using Google. Sign up using Facebook. Sign up using Email and Password. Post as a guest Name. Email Required, but never shown. The Overflow Blog. Read json data into global variable in Node. Asked 9 years, 6 months ago. Active 9 years, 6 months ago.
Viewed 3k times. OrangeDog 32k 12 12 gold badges silver badges bronze badges. Kevin Old Kevin Old 1 1 gold badge 8 8 silver badges 20 20 bronze badges. Add a comment. Active Oldest Votes. With your code as-is, here's what happens: It creates the blank array. It calls readConfig. Later, the readFile operation finishes and the callback is called.
Since it is a Buffer we can use the toString method on the Buffer object to get the contents as String. See this example live in repl. How to get all the contents from a file as String in Node. Published December 13, To get the contents of a file as a string, we can use the readFileSync or readFile functions from the native filesystem fs module in Node.
0コメント