how to add new line using fs.writeFile? - node.js

I tried to write my project's files to a new file, each one in new line, using Node.js. How can I do that? Below is my code:
var fs = require('fs');
var colors = require('colors');
fs.readdir('./', 'utf-8', function(err, data) {
if (err) throw err;
console.log(data);
fs.writeFile('./new.txt', data, function(err) {
if (err) throw err;
console.log('Saved!'.blue);
});
});

You can collect all filenames first and then write them to a file.
const fs = require('fs');
const colors = require('colors');
let fileNames = '';
fs.readdir('./', 'utf-8', function(err, data) {
data.forEach(filename => fileNames += filename + '\n');
fs.writeFile('./new.txt', fileNames, function(err) {
if (err) throw err;
console.log('Saved!'.blue);
});
});

Related

Node.js script to copy files overwriting previous ones?

I wish to create a Node.js script to copy files overwriting previous versions of the same files.
My code doesn't work:
const fs = require('fs');
var src = "srcPath/file.json";
var newPath = "newPath/file.json";
var callback = (result) => {
console.log(result);
}
copy(src, newPath, callback);
function copy(src, newPath, callback){
fs.copyFile(src, newPath, (err) => {
if (err) {
callback("Error Found:", err);
}
else {
callback("Success: "+newPath);
}
});
}
execute()
It will work, if you take this line off:
execute()

Unable to unzip the zipped files using zlib module

I am trying to unzip the files from the zipped data using node build-in module zlib, for some reason I am not able to unzip it, I am getting an error as follows:
Error: incorrect header check
test.js:53
No debug adapter, can not send 'variables'
The code I am trying is as follows:
var zlib = require('zlib');
var fs = require('fs');
var filename = './Divvy_Trips_2019_Q2.zip';
var str1 = fs.createReadStream(filename);
var gzip = zlib.createGunzip();
str1.pipe(gzip).on('data', function (data) {
console.log(data.toString());
}).on('error', function (err) {
console.log(err);
});
The URL to the zipped data is as follows: Divvy_Trips_2019_Q2.zip
GZip (.gz) and ZIP (.zip) are different formats. You need a library that handles ZIP files, like yauzl.
// https://github.com/thejoshwolfe/yauzl/blob/master/examples/dump.js
const yauzl = require("yauzl");
const path = "./Divvy_Trips_2019_Q2.zip";
yauzl.open(path, function(err, zipfile) {
if (err) throw err;
zipfile.on("error", function(err) {
throw err;
});
zipfile.on("entry", function(entry) {
console.log(entry);
console.log(entry.getLastModDate());
if (/\/$/.exec(entry)) return;
zipfile.openReadStream(entry, function(err, readStream) {
if (err) throw err;
readStream.pipe(process.stdout);
});
});
});

Oracle Report Generated PDF is not closing the CreatorDate Bracket in 1 0 obj example /CreatorDate (

I am using FS to read the pdf then replace the CreatorDate>
var fs = require('fs');
fs.readFile('./pdf/0219.PDF', 'utf8', function (err,data) {
if (err) {
return console.log(err);
}
var result = data.replace(/'CreatorDate \('/g, 'Test');
fs.writeFile('./pdf/0219.PDF', result, 'utf8', function (err) {
if (err) return console.log(result, err);
});
});
>

Is it possible to zip data as we write the data in nodejs?

I am able to append data to a file like this
row (this I will get )
fs.appendFile('./file.txt', JSON.stringify(row) + '\n', (err) => {
if (err) throw err;
});
But how can I "append" the data while zipping it at the same time ? I am unsure if this is possible, If yes any pointers will be extremely helpful.
Can I achieve it through piping? if yes how?
zip.appendData('./file.zip',JSON.stringify(row) + '\n', (err) => {
if (err) throw err;
});
Something like above ?
I don't know if it's possible to append to a .zip archive without rewriting it.
If a .gz file is considered, you can use the built-in zlib module to append directly to the .gz file.
const zlib = require('zlib');
zlib.gzip(JSON.stringify(row), (err, data) => {
if (err) throw err;
fs.appendFile('file.txt.gz', data, err => {
if (err) throw err;
})
})
I'm not sure this gonna work, but maybe helps you.
You need zlib package on your project
npm install zlib
Code:
const fs = require('fs');
const zlib = require('zlib');
function WriteAndZip(filename) {
return new Promise(async function (resolve, reject) {
fs.appendFile(`./your_path/${filename}`, JSON.stringify(row) + '\n', (err) => {
if (err) throw err;
});
const fileContents = fs.createReadStream(`./your_path/${filename}`);
const writeStream = fs.createWriteStream(`./your_path/${filename}.gz`);
const zip = zlib.createGzip();
fileContents.pipe(zip).pipe(writeStream).on('finish', (err) => {
if (err) return reject(err);
else resolve();
});
});
}

Why is this readFile operation in Node throwing an error?

I have this code using socket.io on a Node server:
io.sockets.on(
'connection'
,function (socket) {
reader = require('fs');
fileContents = reader.readFile(__dirname + '/textCharacters.txt'
,'utf8'
,function(data, err) {
if (err) throw err;
console.log(data);
}
);
socket.emit('retrievedFileContent', {content:fileContents} );
}
);
When I check the Node server debug, the error shows the contents of the file, so I know the file is being read, but why isn't it being returned to the fileContents variable?
Because the readFile(filename, encoding, callback) function doesn't return the file contents, it passes them as the second argument to the given callback function. Try modifying your code as such:
var fs = require('fs');
io.sockets.on('connection', function (socket) {
var filename = __dirname + '/textCharacters.txt';
fs.readFile(filename, 'utf8', function(err, data) {
if (err) throw err;
socket.emit('retrievedFileContent', {content:data});
});
});

Resources