Блог дизайнера

МЕНЮ
  • Подборки с фотографиями

Изменить json файл node js

JSON (JavaScript Object Notation) is a popular format for sharing data among applications written in different languages. In Node.js applications, JSON has become a convenient choice for storing data thanks to its uniformity and simplicity.

Node.js provides some built-in modules that make it easy to work with JSON data. In this article, you'll learn to:

  • Read JSON files from the disk
  • Write JSON data to a file
  • Use the fs module to interact with the filesystem
  • Use built-in methods like JSON.parse() and JSON.stringify() to convert data from and to JSON format
  • Use the global require() method to load a JSON file at startup

Before I go into details of reading a JSON file, let us first create a new JSON file called databases.json that holds the following JSON data:

The databases.json is a simple file stored on disk that contains a JSON array of objects. Our goal is to read this file and print the records on the console.

To read the JSON data from the above file, you can use the native fs module. This module provides methods to read, write, and watch files along with many other functions to interact with the filesystem. Since it is a native module, you don't need to install anything. Just import it in your code by calling const fs = require('fs') .

The fs module gives us two methods, fs.readFile() and fs.readFileSync() , that can be used to read data from a file. Both these functions do the same thing — reading files from disk. The only difference lies in the way these functions are actually executed.

The fs.readFile() method reads data from a file asynchronously. It doesn't block the execution of the event loop while reading the file. Instead, the control is shifted to the next line to execute the remaining lines of code. Once the file data becomes available, fs.readFile() invokes the callback function passed to it as an argument.

To read the JSON data from the databases.json file by using the fs.readFile() method, just pass in the name of the file, an optional encoding type, and a callback function to receive the file data:

Int the above example, since the fs.readFile() method returns data as a JSON string, we have to use JSON.parse() to parse it to a JSON object. Finally, we use the forEach() loop to print all databases on the console.

Here is the output of the above code:

The fs.readFileSync() method reads data from a file in a synchronous manner. Unlike fs.readFile() , it blocks the execution of the event loop until all the data from the file is loaded.

Instead of passing the callback method, you only pass the name of the file to fs.readFileSync() as shown below:

Although the fs.readFileSync() has a clean syntax, you should never use to read large files as it blocks the execution of the event loop and can drastically impact the performance of the application. It is useful only for reading configuration files on application start before performing any other tasks.

Finally, the last way of reading a JSON file is by using the global require() method. This approach is similar to what you use for loading Node.js modules, but it also works for loading JSON files.

All you need to do is pass the JSON file path to the require() method, and it will synchronously read and parse the JSON file, and return a JSON object ready to be used:

The require() method works exactly like the fs.readFileSync() — read file synchronously, but it is a global method that can be called from anywhere. Moreover, it automatically parses the file content into a JavaScript object.

However, there are a few downsides of using the require() method:

  1. It only reads the file once and cache data; requiring it again with simply return the cached data.
  2. The file must have the .json extension. Without the proper extension, the require() method won't treat it as a JSON file.

Because of the above limitations, require() is only suitable for loading static configuration files that don't change often. For reading a dynamic file like databases.json , you should use the fs.readFile() method instead.

Just like fs.readFile() and fs.readFileSync() method, the fs module provides two more functions for writing data files: fs.writeFile() and fs.writeFileSync() .

As the names suggest, the fs.writeFileSync() method writes data to a file synchronously while fs.writeFile() writes data to a file in an asynchronous manner.

To write JSON to a file by using fs.writeFile() , just pass in the path of the file to write data to, the JSON string that you want write, an optional encoding type, and a callback function that will be executed after the file is written.

Note that if the file doesn't already exist, it will be created; if it does exist, it will be overwritten!

Here is an example:

In the above example, we are storing the JSON object user to the user.json file.

Notice the use of the JSON.stringify() method to convert the JSON object into a JSON string before saving it to disk. If you try to write an object to a file without first stringifying it, your file will be empty and look like below:

Now if you execute the above code, you should see the following content in the user.json file:

Technically, that's all you need to write JSON to a file. However, the data is written as a single line of string in the file.

To pretty-print the JSON object, change the JSON.stringify() method as follows:

Now, if you open the user.json file, you should see the following content:

Finally, the last way to write data to a JSON file is by using the fs.writeFileSync() method. It writes data to a file synchronously which means it blocks the execution of the Node.js event loop until the file is written to disk.

Take a look at the following example that uses fs.writeFileSync() to write a JSON object to a file:

Now that we have learned how to read and write JSON files, what if you want to update an existing JSON file?

We can combine both these approaches to use our JSON files as a simple database. Whenever we want to update the data in the JSON file, we can read the contents, change the data, and then write the new data back to the original file.

Here is an example that demonstrates how you can add another record to the databases.json file:

Now, if you execute the above code, you should see a new entry in databases.json as shown below:

If you don't want to manually parse or stringify JSON data each time you read or write to a JSON file, use the jsonfile module instead.

The jsonfile module wraps the fs module and JSON object methods and exposes the same methods as the fs module for reading and writing JSON files.

Type the following command in your project root directory to install the jsonfile module:

To read data from JSON files, the jsonfile module provides readFile() and readFileSync() methods. They are similar to those offered by the fs module except that they automatically parse the contents of the file into a JSON object:

Similarly, to write data to a JSON file, you can either use the writeFile() or writeFileSync() method:

JSON is one of the most popular types of data that you expect to work in Node.js, and being able to read and write JSON files is extremely useful.

In this article, we have looked at different ways to read and write JSON files, including the fs module, the require() method, and the jsonfile module — a 3rd-party module.

The fs module is a native module that provides functions for both reading and writing files. The fs.readFile() and fs.writeFile() methods can be used to read and write data to JSON files asynchronously. To synchronously interact with the filesystem, there are fs.readFileSync() and fs.writeFileSync() methods available.

You can also use the global require() method to synchronously read and parse a JSON file at startup. However, it only caches the file data and can only be used to read files with the .json extension.

If you want to learn more, take a look at what JSON actually is, and how you can read and write a JSON object to a file in Node.js.

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.

Buy Me A Coffee

Appends a value/object to a specific path. If the path is empty it wil create a list.

Params

  • String path : The object path.
  • Anything value : The value.

Return

  • JsonEditor The JsonEditor instance.

4. Отметьте


Теперь имитируйте пейджинг
Сначала посмотрите, как выглядит файл json

загрузить код



Посмотрим на вторую страницу
выполнить pagination(1,6);
Результат выполнения:

и т. д., чтобы добиться эффекта имитации разбиения по страницам.

Учить больше

Хотите узнать больше об основах Node.js? Лично я бы порекомендовал пройти онлайн-курс, например Learn Node.js от Веса Боса . Вы не только изучите самый современный синтаксис ES2017, но и сможете создать полноценное ресторанное приложение. По моему опыту, создание подобных реальных приложений - самый быстрый способ учиться.

Запись JSON в файл

Подобно readFile и readFileSync , есть две функции для записи данных в файлы : writeFile и writeFileSync . Как следует из названий, writeFile записывает данные в файл асинхронным способом, в то время writeFileSync функция writeFileSync записывает данные в файл синхронным образом.

Мы рассмотрим подробнее в следующих разделах.

Использование fs.writeFileSync

Функция writeFileSync принимает 2-3 параметра: путь к файлу для записи данных, данные для записи и необязательный параметр.

Обратите внимание: если файл еще не существует, для вас создается новый файл. Взгляните на следующий пример:

В приведенном выше примере мы сохраняем наш объект JSON student в файл с именем «student-2.json». Обратите внимание, что здесь мы должны использовать JSON.stringify перед сохранением данных. Точно так же, как нам нужно было проанализировать данные в формате JSON, когда мы читаем файл JSON, нам нужно «преобразовать» данные в строку, прежде чем мы сможем сохранить их в строковой форме в файле.

Выполните приведенный выше код и откройте файл student-2.json. Вы должны увидеть в файле следующее содержимое:

Хотя это данные, которые мы хотели записать, они представлены в виде одной строковой строки, которую нам трудно прочитать. Если вы хотите, чтобы сериализованный JSON был удобочитаемым человеком, измените JSON.Stringify следующим образом:

Здесь мы говорим методу добавить новые строки и пару отступов в сериализованный JSON. Теперь, если вы откроете файл "student-2.json", вы должны увидеть текст в следующем формате.

Использование fs.writeFile

Как я уже говорил ранее, writeFile функция выполняется в асинхронном режиме, что означает наш код не блокируется , а данные записываются в файл. И, как и в случае с асинхронными методами ранее, нам нужно передать обратный вызов этой функции.

Давайте напишем еще один файл, student-3.json, с writeFile функции writeFile.

Результатом вышеупомянутого скрипта будет:

И снова вы можете видеть, что последняя строка нашего кода фактически отображается первой в консоли, поскольку наш обратный вызов еще не был вызван. Это приводит к значительной экономии времени выполнения, если у вас есть большие объемы данных для записи в файл или если у вас довольно много файлов для записи.

1. увеличить


Во-первых, давайте посмотрим на структуру демонстрационных каталогов.


Давайте посмотрим на содержимое person.json

Ничего страшного, следующий момент, чтобы стать свидетелем чуда
Напишите код nodejs ниже


Результат выглядит следующим образом

Давайте посмотрим на результат файла json.



Смотрите, файл json добавлен

2. Удалить




Пятый удален

5. Резюме

Хорошо, был написан набор основных дополнений, удалений и изменений. Я чувствую, что этот узел по-прежнему очень мощный, и я чувствую, что я немного улучшился. Хотя некоторые люди могут подумать, что писать таким образом, возможно, бессмысленно, но я думаю, что это очень важно. Получите много! ! !

Один из лучших способов обмена информацией между приложениями, написанными на разных языках, - это использование формата JSON (JavaScript Object Notation). Благодаря единообразию и простоте JSON почти полностью заменил XML в качестве стандартного формата обмена данными в программном обеспечении, особенно в веб-сервисах.

Учитывая широкое использование JSON в программных приложениях, и особенно в приложениях на основе JavaScript, важно знать, как читать и записывать данные JSON в файл в Node.js. В этой статье мы объясним, как выполнять эти функции.

toObject()

Return

pop(path)

Pop an array from a specific path.

Params

  • String path : The object path.

Return

  • JsonEditor The JsonEditor instance.

read(The, cb)

write Write the JSON file.

Params

  • String The : file content.
  • Function cb : An optional callback function which will turn the function into an asynchronous one.

Return

  • JsonEditor The JsonEditor instance.

empty(cb)

Empty the JSON file content.

Params

  • Function cb : The callback function.

save(cb)

Save the file back to disk.

Params

  • Function cb : An optional callback function which will turn the function into an asynchronous one.

Return

  • JsonEditor The JsonEditor instance.

💫 Where is this library used?

If you are using this library in one of your projects, add it in this list. ✨

How do I update a value in a json file and save it through node.js? I have the file content:

Now I want to change the value of val1 and save it to the file.

Чтение файла JSON

Давайте сначала посмотрим, как мы можем прочитать уже созданный файл. Но прежде чем мы это сделаем, нам нужно создать файл. Откройте новое окно в вашем любимом текстовом редакторе и добавьте в него следующий текст:

Теперь сохраните этот файл как «student.json» в каталоге вашего проекта.

Чтобы прочитать данные JSON из файла, мы можем использовать модуль Node.js fs. В этом модуле доступны две функции, которые мы можем использовать для чтения файлов из файловой системы: readFile и readFileSync .

Хотя обе эти функции выполняют схожие задачи, например, читают файлы с диска, разница заключается в том, как эти функции выполняются на самом деле, что мы объясним более подробно в следующих разделах.

Использование fs.readFileSync

Функция readFileSync считывает данные из файла. Эта функция блокирует выполнение остальной части кода до тех пор, пока все данные не будут прочитаны из файла. Эта функция особенно полезна, когда вашему приложению необходимо загрузить параметры конфигурации, прежде чем оно сможет выполнять какие-либо другие задачи.

Чтобы продолжить наш пример, давайте воспользуемся этой функцией для чтения файла "student.json", который мы создали ранее, с readFileSync функции readFileSync. Добавьте следующий код в файл .js:

В приведенном выше коде Node.js мы сначала загружаем fs в наше приложение. Затем мы используем readFileSync и передаем ей относительный путь к файлу, который мы хотим прочитать. Если напечатать объект rawdata на консоль, вы увидите исходные данные (в буфере ) на экране консоли:

Однако мы хотим читать файл в его формате JSON, а не необработанные шестнадцатеричные данные. Здесь в JSON.parse вступает функция JSON.parse. Эта функция обрабатывает синтаксический анализ необработанных данных, преобразует их в текст ASCII и анализирует фактические данные JSON в объект JavaScript. Теперь, если вы распечатаете student на консоли, вы получите следующий вывод:

Как видите, JSON из нашего файла был успешно загружен в объект student

Использование fs.readFile

Другой способ чтения файла JSON в Node.js - использование функции readFile В отличие от функции readFileSync readFile считывает данные файла асинхронно. Когда readFile функция readFile, начинается процесс чтения файла, и сразу же управление переходит к следующей строке, выполняющей оставшиеся строки кода. После загрузки данных файла эта функция вызовет предоставленную ей функцию обратного вызова. Таким образом, вы не блокируете выполнение кода, ожидая, пока операционная система вернется к вам с данными.

В нашем примере readFile принимает два параметра: путь к файлу, который должен быть прочитан, и функцию обратного вызова, которая должна быть вызвана, когда файл будет полностью прочитан. При желании вы также можете включить параметр с параметрами, но мы не будем рассматривать их в этой статье.

Взгляните на следующий пример, чтобы понять, как использовать функцию readFile

Приведенный выше код делает то же самое, что и наш предыдущий фрагмент кода (с дополнительным console.log ), но делает это асинхронно. Вот несколько отличий, которые вы, возможно, заметили:

  • (err, data) =><> : это наша функция обратного вызова, которая выполняется после полного чтения файла.
  • err : Так как мы не можем легко использовать попробовать / поймать с асинхронным кодом, функция вместо дает нам err объект , если что - то пойдет не так. null если ошибок не было

Вы также могли заметить, что мы readFile строку в консоль сразу после вызова readFile. Это сделано для того, чтобы показать вам поведение асинхронного кода. Когда приведенный выше сценарий будет выполнен, вы увидите, что этот console.log выполняется до выполнения readFile обратного вызова readFile. Это связано с тем, что readFile не блокирует выполнение кода при чтении данных из файловой системы.

Вывод кода будет выглядеть так:

Как видите, последняя строка кода в нашем файле на самом деле является той, которая появляется первой в выводе.

Использование require

Другой подход - использовать глобальный require для чтения и анализа файлов JSON. Это тот же метод, который вы используете для загрузки модулей Node, но его также можно использовать для загрузки JSON.

Взгляните на следующий пример.

Он работает точно так же, как readFileSync мы показали выше, но это глобально доступный метод, который вы можете использовать где угодно, что имеет свои преимущества.

Однако у функции require есть несколько недостатков:

  • Require - это синхронная функция, которая вызывается только один раз, что означает, что вызовы получают кешированный результат. Если файл обновлен, вы не можете перечитать его с помощью этого метода.
  • Ваш файл должен иметь расширение .json, поэтому он не может быть таким гибким. Без правильного расширения require не обрабатывает файл как файл JSON.

💖 Support my projects

I open-source almost everything I can, and I try to reply to everyone needing help using these projects. Obviously, this takes time. You can integrate and use these projects in your applications for free! You can even change the source code and redistribute (even resell it).

However, if you get some profit from this or just want to encourage me to continue creating stuff, there are few ways you can do it:

Starring and sharing the projects you like 🚀

—I love books! I will remember you after years if you buy me one. 😁 📖

—You can make one-time donations via PayPal. I'll probably buy a coffee tea. 🍵

—Set up a recurring monthly donation and you will get interesting news about what I'm doing (things that I don't share with everyone).

Bitcoin—You can send me bitcoins at this address (or scanning the code below): 1P9BRsmazNQcuyTxEqveUsnf5CERdq35V6


editJsonFile(path, options)

Edit a json file.

Params

  • String path : The path to the JSON file.
  • Object options : An object containing the following fields:

Return

  • JsonEditor The JsonEditor instance.

7 Answers 7

Doing this asynchronously is quite easy. It's particularly useful if you're concerned with blocking the thread (likely). Otherwise, I'd suggest Peter Lyon's answer

The caveat is that json is written to the file on one line and not prettified. ex:

To avoid this, simply add these two extra arguments to JSON.stringify

null - represents the replacer function. (in this case we don't want to alter the process)

2 - represents the spaces to indent.

Overall, it would be better to use an async write as this is the main focus of Node. Of course, without seeing the surrounding code it would be hard to give a definitive answer. It is unlikely that you would really need a sync unless you are need to be absolutely sure nothing else can happen until the write has completed. Additionally, of course, this should have an error checker since you can NEVER be sure that a file write will succeed.

async vs. sync depends exactly on what you are doing in what context. If this is in a network service, you need async. For a command line utility, sync is the appropriate paradigm in most simple cases, but just knee-jerk saying "async is better" is not correct. My snippet is based on the OP snippet for context. The question is also not about error handling and if the file write fails, exiting with a stack trace is reasonable default behavior because there's not much you can do to recover from that.

Because node is loop based, async is nearly always better so you don't block the loop, this isn't a knee-jerk reaction at all, simply standard practice for node Dev. I already said that it depends on the requirement and I don't think the Q says anything about command line? Also in general, if this is part of a larger set of code (not clarified by the OP), then error handling is always smart and best practice. Dumping a stack trace is ok for Devs but crap for everyone else.

async is a concurrency technique. If you need concurrency, async is required for node to work properly (not "better"). If you don't have concurrency, you don't need async. The point is you need to actually understand what async does for you and why. It's not inherently "better" for no reason and you don't need to memorize it as a "best practice". If the OP is writing a command line utility to alter a JSON file then exit, async complicates the code for no reason as the concurrency is not required.

I am building a node command line tool. If it is not sync written, the file could be locked when the output of my tool gets chained to the next tool. There are very good reasons to use sync. And good reasons to use async.

read(cb)

Read the JSON file.

Params

  • Function cb : An optional callback function which will turn the function into an asynchronous one.

Return

  • Object The object parsed as object or an empty object by default.

pop(path)

Pop an array from a specific path.

Params

  • String path : The object path.

Return

  • JsonEditor The JsonEditor instance.

😋 How to contribute

Have an idea? Found a bug? See how to contribute.

3. Изменить


Исходный файл json выглядит так


Результат выглядит следующим образом


Взгляните на файл json

Заключение

В этой статье мы показали, как вы можете читать и записывать данные JSON из файлов и в файлы, что является очень распространенной и важной задачей, которую нужно знать, как веб-программист.

fs есть несколько методов как для чтения, так и для записи в файлы JSON. Функции readFile и readFileSync будут читать данные JSON из файла асинхронно и синхронно соответственно. Вы также можете использовать глобальный require для обработки чтения / анализа данных JSON из файла в одной строке кода. Однако require является синхронным и может читать данные JSON только из файлов с расширением .json.

Точно так же функции writeFile и writeFileSync из fs записывают данные JSON в файл асинхронным и синхронным образом соответственно.

Используйте nodejs для добавления, удаления, изменения и проверки локальных файлов json

Здравствуйте! Файловая система nodejs. Те, кто был в контакте с node, обязательно будут знакомы с файловой системой node. Я думал над вопросом в последние два дня. Могу ли я управлять своим локальным файлом json локально, чтобы локальная текстовая база данных была доступна , Если это стикер, записывающее программное обеспечение, мне вообще не нужно подключаться к серверной базе данных, я могу управлять локальным файлом json самостоятельно и самостоятельно писать серверную часть с помощью узла. Ответ - да, давайте реализуем это вместе, правильно Добавить, удалить, изменить и проверить локальные файлы json

Читайте также:

      
  • Взрослый сын не работает сидит за компьютером
  •   
  • Ide 44 pin распиновка
  •   
  • Lockdown mode vmware что это
  •   
  • Можно ли отправить возражение на судебный приказ по электронной почте без электронной подписи
  •   
  • Forge exe warcraft 3 где файл
  • Контакты
  • Политика конфиденциальности