0

I have installed node.js and running a project(with all js files) on Apache Knox. I need to save some data to a file(HOME/Job_State.txt) in Linux FS and read its contents when needed to do some checksums. Iam new to js and looking for example code that does this. Kindly help me by providing some suggestions/pointers.

1 Answer 1

4

Have a look at the fs (File System) module of node.js:

var fs = require('fs');

fs.writeFile('message.txt', 'Hello Node', function (err) {
  if (err) throw err;
  console.log('It\'s saved!');  
});

fs.readFile('message.txt', function (err, data) {
  if (err) throw err;
  console.log(data);
});

https://nodejs.org/api/fs.html#fs_fs_writefile_filename_data_options_callback

https://nodejs.org/api/fs.html#fs_fs_readfile_filename_options_callback

There are synchronous versions too: fs.writeFileSync() and fs.readFileSync()

Sign up to request clarification or add additional context in comments.

2 Comments

I assume console.log would print the data into logs. Is there a way to get the data into a variable so that I can use regex expressions to separate and validate contents of the file. Please correct me if Iam wrong.
console.log prints with newline to stdout. data is already a variable that you can use with regex!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.