Skip to content
Advertisement

write/read contents from a file in Linux FS using java script

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.

Advertisement

Answer

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()

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement