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
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()
2 Comments
Atom
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.
dsuckau
console.log prints with newline to stdout. data is already a variable that you can use with regex!