LoginSignup
1
0

More than 3 years have passed since last update.

Node.jsを勉強する② - テキストファイルの作成方法

Last updated at Posted at 2021-01-03

はじめに

前回は、Node.jsの環境構築についてまとめました。今回はテキストファイルの作成方法を記事にします。

教材

Udemy
The Complete Node.js Developer Course (3rd Edition)
https://www.udemy.com/course/the-complete-nodejs-developer-course-2/

Jsファイルの作成とファイルモジュールの導入

まずは、コードを書くファイルを作成します。今回はnodeapp.jsと名付けます。
次に、app.jsの中にrequireを用いファイルを操作するモジュールを導入します。
constを用いて変数fsを定義し、モジュールの中身を代入します。

nodeapp.js
const fs = require('fs')

テキストファイルを作成する

次に、"writeFileSync"メソッドを用いて、テキストファイルを作成し、文字も入れます。
カッコの中の一つ目の要素はファイル名、2つ目の要素は、書く文字になります。

nodeapp.js
//ファイルモジュールを導入
const fs = require('fs')
//ファイルを作成し、文字を書く
fs.writeFileSync('notes.txt', 'Hello, this is the first message!')

実行するにはターミナルにnode ファイル名と入力します。

ターミナル
node nodeapp.js

文字を追加する

文字を追加するには、appendFileSyncメソッドを使います。
カッコの中の一つ目が

nodeapp.js
//ファイルを作成し、文字を追加する
fs.appendFileSync('notes.txt', 'Hello, this is the first message!')

再度実行して、動作を確認しましょう

ターミナル
node nodeapp.js

テキストファイルを確認して、文字が追加されていれば、完成です。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0