Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
学ぶ Writing Files | Section
Node.js Fundamentals

bookWriting Files

メニューを表示するにはスワイプしてください

Writing files is a fundamental task in Node.js, and you will often need to save data such as logs, notes, or configuration information to disk. Node.js provides the fs (file system) module, which includes methods for writing files both asynchronously and synchronously. When you write to a file, you can either create a new file or overwrite the contents of an existing one. This is an important concept to understand because writing to a file with these methods will replace all the content that was previously in the file.

const fs = require('fs');

fs.writeFileSync('notes.txt', 'My first note');

This code creates a new file called notes.txt in the current directory and writes "My first note" into it. If notes.txt already exists, its entire content will be replaced with the new string. This behavior is important to remember: writing to a file using fs.writeFileSync or fs.writeFile always replaces the existing content of the file.

const fs = require('fs');

fs.writeFile('notes.txt', 'My updated note', (err) => {
  if (err) {
    console.error('Failed to write file:', err);
    return;
  }
  console.log('Note saved!');
});
Note
Note

Key concept: writing to a file using fs.writeFile or fs.writeFileSync will always replace any existing content in that file. If you want to add to the existing content instead, you will need to use a different method.

When you save notes, logs, or any other data to a file in Node.js, understanding the difference between synchronous and asynchronous file writing, as well as the fact that writing will replace previous content, is essential for avoiding accidental data loss and for choosing the right tool for your specific task.

すべて明確でしたか?

どのように改善できますか?

フィードバックありがとうございます!

セクション 1.  22

AIに質問する

expand

AIに質問する

ChatGPT

何でも質問するか、提案された質問の1つを試してチャットを始めてください

セクション 1.  22
some-alt