Clear the content of text file in node.js - node.js

This is my code for JScript file
fs.open("SensorDataValue.txt",'a' , function(err, fd) {
if(err) {
throw 'error opening file: ' + err;
}
fs.write(fd, buffer, 0, buffer.length, null, function(err) {
if (err) throw 'error writing file: ' + err;
fs.close(fd, function() {
console.log("V 14 The file was saved!" + "\r\n");
});
This will keep appending any text to the 'SensorDataValue" text file.
However, what I want to achieve is :
To clear the content of text file before it appends. So every time, I use the script file, it will always clear the text file FIRST before appending any data in it.
How do I go about achieving this?

var data = 'Hello World!!'
var fs = require('fs');
fs.unlink(__dirname + '/proto.js', (err) => {
if (err) {
console.log(err);
}
writeData(data)
})
function writeData(data) {
fs.writeFile(__dirname + '/proto.js', data, (err, data) => {
if (err) {
console.log(err, data);
} else {
console.log('Data uploaded')
}
})
}

Related

NODE JS - Delete all files execept content list

My function is:
function Delete(dir){
log(`[DELETE] ${dir}.`)
fs.readdir(dir, (err, files) => {
if (err) {
console.log(err);
}
files.forEach(file => {
const fileDir = path.join(dir, file);
if (file !== 'specialfile.txt') {
fs.rm(fileDir, { recursive:true }, (err) => {
if(err){
// File deletion failed
console.error(err.message);
return;
}
})
}
});
});
But he only preserves the "specialfile.txt" not the content file in case i like preserver a list of files inside in "specialfile.txt".
specialfile.txt:
error.dll
Windows.txt
jose.cfg

Looping console.log fine, but only add one row in file node.js

Cant really understand what I do wrong here. Everything loops fine in the console.log but in the file I only get the last one. I quessing it is overwriting the file everytime?
readFiles('/Volumes/Staccs_Sled_001/Eagle Rock 2 Oktober - Exported', (filepath, name, ext, stat) => {
console.log('file path:', filepath);
console.log('file name:', name);
console.log('file extension:', ext);
console.log('file information:', stat);
const infotext = [
ext,
filepath,
]
fs.writeFileSync('./exportedTitles.json', JSON.stringify(infotext, null, 2), err => {
if (err) {
console.log(err);
} else {
console.log('files made');
}
})
})
Any suggestions what I doing wrong?
fs.writeFileSyncoverwrites the file.
You will have to use fs.appendFile
fs.appendFile('./exportedTitles.json', 'data to append', err => {
if (err) {
console.log(err);
} else {
console.log('files made');
}
});

How to manipulate files line by line based on certain criterias

I need to read a file line by line and write newlines to same file while reading, if each line satisfy certain set of conditions. What could be the best way.
function (file, callback) {
fs.readFile(file, (err, 'utf8', data) => {
if (err) return callback(err);
var lines = data.split('\n');
fs.open(file, 'w', (err, fd) => {
if (err) return callback(err)
lines.forEach(line => {
if (line === 'meet your condition') {
// do your write using fs.write(fd, )
}
})
callback();
})
})
}
use node fs module with the help of fs you can perform operation asynchronously as well as synchronously. below is as an example of asynchronously
function readWriteData(savPath, srcPath) {
fs.readFile(srcPath, 'utf8', function (err, data) {
if (err) throw err;
//Do your processing, MD5, send a satellite to the moon or can add conditions , etc.
fs.writeFile (savPath, data, function(err) {
if (err) throw err;
console.log('complete');
});
});
}
Synchronously example
function readFileContent(srcPath, callback) {
fs.readFile(srcPath, 'utf8', function (err, data) {
if (err) throw err;
callback(data);
}
);
}
function writeFileContent(savPath, srcPath) {
readFileContent(srcPath, function(data) {
fs.writeFile (savPath, data, function(err) {
if (err) throw err;
console.log('complete');
});
});
}

NodeJs - graphicsMagic writes empty images

I'm resizing an image using gm library but it create an empty image. I use different ways for writing result but everytime get empty image.
gm(readStream)
.size({bufferStream: true}, function(err, size) {
this.resize(100, 100, '%')
.stream()
.on('end',function(){
console.log('done');
})
.on('error',function(err){
console.log(err);
})
.pipe(writeStream);
});
I also use this way but result was the same.
gm(srcPath)
.resize(100, 100)
.stream(function(err, stdout, stderr) {
if(err){
console.log('ERRoor:', err);
}
// ws = fs.createWriteStream( output );
i = [];
stdout.on( 'data', function(data){
// console.log('data');
i.push( data );
});
stdout.on( 'close', function(){
console.log( 'close' );
var image = Buffer.concat( i );
writeStream.write( image.toString('base64'), 'base64' );
writeStream.end();
});
});
And this way too:
gm(srcPath)
.resize(100, 100)
.write(writeStream, function (err) {
var thumbUrl, error;
if (err) {
error = err;
} else{
thumbUrl = thumbPath.replace(/\\/g, '/');
thumbUrl = thumbUrl.replace(/^\.\/public/, '');
}
callback(error, thumbUrl);
});
this way every time return en empty object({}) as error!

how to recover from createWriteStream error and continue to pipe?

when using busboy to handle file upload in node.js
var uploadStream = fs.createWriteStream(imagePath);
uploadStream.on('error', function(err) {
if (err.code === 'ENOENT') {
// unknown dir
mkdirp(imageDir, function(err) {
if (err) {
throw new Error('mkdirp error in upload')
} else {
// how to continue pipe from here?
}
})
}
});
file.on('data', function(data) {
console.log('File [' + fieldname + '] got ' + data.length + ' bytes');
});
file.on('end', function() {
console.log('File [' + fieldname + '] Finished');
});
// save uploaded file
file.pipe(uploadStream);
if createWriteStream with an unexist dir,then an error event is fired, and I tried to handle this error by create that dir and continue the upload pipe, but I dont know how to continue the upload I tried something like
uploadStream.on('error', function(err) {
if (err.code === 'ENOENT') {
// unknown dir
mkdirp(imageDir, function(err) {
if (err) {
throw new Error('mkdirp error in upload')
} else {
file.pipe(uploadStream) // not work
file.pipe(fs.createWriteStream(imagePath)) // only get a part of uploaded image
}
})
}
// uploadStream.end();
});
please help!!!

Resources