Im trying to write into a text file in node.js.
Im doing this the following way:
fs.writeFile("persistence\\announce.txt", string, function (err) {
if (err) {
return console.log("Error writing file: " + err);
}
});
whereas string is a variable.
This function will begin it`s writing always at the beginning of a file, so it will overwrite previous content.
I have a problem in the following case:
old content:
Hello Stackoverflow
new write:
Hi Stackoverflow
Now the following content will be in the file:
Hi stackoverflowlow
The new write was shorter then the previous content, so part of the old content is still persistent.
My question:
What do I need to do, so that the old content of a file will be completely removed before the new write is made?
You can try truncating the file first:
fs.truncate("persistence\\announce.txt", 0, function() {
fs.writeFile("persistence\\announce.txt", string, function (err) {
if (err) {
return console.log("Error writing file: " + err);
}
});
});
Rename the old file and append to therefore a non existent file (creating a new one). This way you have on the one hand a backup and on other hand a fresh updated file ./config.json:
fs.renameSync('./config.json', './config.json.bak')
fs.appendFileSync('./config.json', text)
(sync version, might throw)
Related
If i have the code below how can i edit the specific file and make the right corrections?
var p4 = require('C:/Program Files/nodejs/node_modules/p4');
var File = process.argv[2];
p4.edit(File, function(err, data) {
if (err) {
console.error(err.message);
}
console.log(data);
});
Your code looks correct to open the file for edit. If that returns any errors when you run it, you should post those here, but I'll assume that it returns a success message ("(file) opened for edit").
Opening the file for edit means that it is made writable on the local filesystem (i.e. the one where this code is running -- the file is the one you passed as an argument to the edit command). To actually modify the file you can use any other function at your disposal.
I'm trying to read the contents from a CSV file using readAsText ngCordova plugins.
I can do it only when the encoding of file is unicode, but most CSV files are Shift-JIS. And I can read nothing from the file when it is Shift-JIS
My code likes below:
$cordovaFile.readAsText(cordova.file.documentsDirectory + CSVS_DIR, fileName).then(
function (success) {
console.log("reading csv");
console.log("csv content: " + success);
},
function (error) {
console.log(error);
// error
});
Is there any one know how to deal with it?
Thanks a lot.
After a whole day on this issue, I finally find out the answer.
Unfortunately, the answer is NO. We cannot achieve it by using readAsText.
According to the docs of ngCordova, the API do not support the encoding parameter in readAsText function as the cordova-file-plugin has.
Besides, after I read the document of codova-file-plugin, I realized that the readAsText function in Cordova-file-plugin does not support the encoding parameter when it runs in ios.
SOLUTION
As readAsText cannot do this, I tried the other functions provided in ngCordova. And I found readAsBinaryString. This function seems just read the content of file no matter what the encoding it is. So, I can read the content and encode it into Unicode by encoding.js.
codes:
$cordovaFile.readAsBinaryString(cordova.file.documentsDirectory + CSVS_DIR, fileName).then(
function (success) {
console.log("reading csv");
console.log("csv content: " + success);
var detected = Encoding.detect(success);
success = Encoding.convert(success, {
to: 'UNICODE', // to_encoding
from: detected // from_encoding
});
console.log("csv content: " + success);
},
function (error) {
console.log(error);
// error
});
Hope my solution can help.
I have a set of html and js files that needs translating. Instead of traditionally copying pasting each keys to a json file, I was wondering if there was a way to do this faster by building a Node JS script. I have a JS script currently which traverses recursively on the directory. And, able to read the current file which is being traversed. But, I want to only extract angular elements that needs to be translated. {{"Welcome" | translate}} <-- HTML $scope.word = {$translate.instant('Export Attendance'); <-- JS Controller
Basically, these are the patterns I want my program to look out for, and only capture the strings into another seperate JSON file.
Currently I have a program that is below.
get_translations.js
var read = require('recursive-readdir-sync');
var fs = require('fs');
try {
root = read('./files/that/has/html/and/js');
} catch (err) {
if (err) {
console.log("File does not exist");
} else {
throw err;
}
}
for (var a=0; a<root.length; a++) {
console.log(root[a]);
fs.readFile(root[a], 'utf-8', function(err, data) {
if (err) {
throw err;
} else {
console.log(data); //need help here.. (noob)
}
});
}
I'd like to avoid JQuery as much as possible. Any light shed on the matter will be greatly apprecieated.
Thanks.
Noob Javascript
I am using node.js, trying to save a file, no errors are thrown, yes the image won't save. This is how I am saving the file:
var url = 'captures/' + getFileName() + '.png';
fs.writeFile(url, base64, 'base64', function(err) {
if(err) {
console.log(err);
} else {
console.log("The file was saved!");
}
});
With a helper to make the file names for me:
function getFileName(){
var d = new Date()
return d.getMonth()+'-'+d.getDate()+'-'+d.getYear()+'-'+d.getHours()+'-'+d.getMinutes()+d.getSeconds();
}
Anyone had trouble with this?
the problem is because this call is async and probably is loosing the context right after, I was able to fix it on my end by using fs.writeFileSync which does it synchronously. hope this helps
Add a console.log('captures/' + getFileName()) just to make sure your file name is correct. When I had this problem it turned out that I had a problem with the file path/name and node just wasn't throwing me an error to explain.
For Typescript version,
Just sharing my experience here, In my use case had a JSON file where I used to store some temporary data read it and make some changes and update it and store that updated data to same JSON file will be used for next cycle.
fs.writeFile was not throwing any error at same time it was not updating my JSON file where as JS version worked well, Then I realized that typescript made these changes in my root or src directory. Created another JSON file there.
If you want to write your file asynchronously, try using fs/promises instead of fs.
const { writeFile } = require("fs/promises");
(async () => {
await writeFile('myFile.txt', 'my content', (err) => {});
})();
writeFile from fs is void. It will execute asynchronously but not in the async-await meaning. writeFile from fs/promises returns a Promise so async-await will work as expected.
Learn more here: https://nodejs.org/api/fs.html#callback-example
There might be a permission issue.
go inside the directory that you are saving your files and then
sudo chmod 777 .
I am writing multiple files via fs.createWriteStream.
I want to alter the Last Modified value to a specific time-stamp, but I am having a hard time figuring out how to achieve this, I need some directions to get it working.
I'm using this code, in a loop that has a file argument.
var stream = fs.createWriteStream(__dirname + '/images/' + file.id + file.ext, { flags: 'w', encoding: null, mode: 0666 });
stream.on('finish', function(data) {
fs.utimes(stream.path, file.ts, file.ts, function (err) {
if (err) { throw err; }
console.log('>> Set mtime to: '+ file.ts);
});
});
client.getBlob(file.id).then(function(blob) {
blob.pipe(stream);
});
It's logging the correct things on the finish event, but in windows my modified dates are the time that the file was created.
Node version is 0.10.25.
Once stream has finished its operation and closed, perhaps a quick open and append of one character to the file will set a last modified date closer to what you want?