Create an account

Very important

  • To access the important data of the forums, you must be active in each forum and especially in the leaks and database leaks section, send data and after sending the data and activity, data and important content will be opened and visible for you.
  • You will only see chat messages from people who are at or below your level.
  • More than 500,000 database leaks and millions of account leaks are waiting for you, so access and view with more activity.
  • Many important data are inactive and inaccessible for you, so open them with activity. (This will be done automatically)


Thread Rating:
  • 347 Vote(s) - 3.6 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Writing to files in Node.js

#1
I've been trying to find a way to write to a file when using Node.js, but with no success. How can I do that?
Reply

#2
var path = 'public/uploads/file.txt',
buffer = new Buffer("some content\n");

fs.open(path, 'w', 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('file written');
})
});
});
Reply

#3
You can of course make it a little more advanced. Non-blocking, writing bits and pieces, not writing the whole file at once:

var fs = require('fs');
var stream = fs.createWriteStream("my_file.txt");
stream.once('open', function(fd) {
stream.write("My first row\n");
stream.write("My second row\n");
stream.end();
});
Reply

#4
You can use library `easy-file-manager`

install first from npm
`npm install easy-file-manager`

Sample to upload and remove files

var filemanager = require('easy-file-manager')
var path = "/public"
var filename = "test.jpg"
var data; // buffered image

filemanager.upload(path,filename,data,function(err){
if (err) console.log(err);
});

filemanager.remove(path,"aa,filename,function(isSuccess){
if (err) console.log(err);
});

Reply

#5
var fs = require('fs');
fs.writeFile(path + "\\message.txt", "Hello", function(err){
if (err) throw err;
console.log("success");
});

For example : read file and write to another file :

var fs = require('fs');
var path = process.cwd();
fs.readFile(path+"\\from.txt",function(err,data)
{
if(err)
console.log(err)
else
{
fs.writeFile(path+"\\to.text",function(erro){
if(erro)
console.log("error : "+erro);
else
console.log("success");
});
}
});

Reply

#6
Here is the sample of how to read file csv from local and write csv file to local.

var csvjson = require('csvjson'),
fs = require('fs'),
mongodb = require('mongodb'),
MongoClient = mongodb.MongoClient,
mongoDSN = 'mongodb://localhost:27017/test',
collection;

function uploadcsvModule(){
var data = fs.readFileSync( '/home/limitless/Downloads/orders_sample.csv', { encoding : 'utf8'});
var importOptions = {
delimiter : ',', // optional
quote : '"' // optional
},ExportOptions = {
delimiter : ",",
wrap : false
}
var myobj = csvjson.toSchemaObject(data, importOptions)
var exportArr = [], importArr = [];
myobj.forEach(d=>{
if(d.orderId==undefined || d.orderId=='') {
exportArr.push(d)
} else {
importArr.push(d)
}
})
var csv = csvjson.toCSV(exportArr, ExportOptions);
MongoClient.connect(mongoDSN, function(error, db) {
collection = db.collection("orders")
collection.insertMany(importArr, function(err,result){
fs.writeFile('/home/limitless/Downloads/orders_sample1.csv', csv, { encoding : 'utf8'});
db.close();
});
})
}

uploadcsvModule()
Reply

#7
I liked *[Index of ./articles/file-system][1]*.

It worked for me.

See also *[How do I write files in node.js?][2]*.

fs = require('fs');
fs.writeFile('helloworld.txt', 'Hello World!', function (err) {
if (err)
return console.log(err);
console.log('Wrote Hello World in file helloworld.txt, just check it');
});

Contents of helloworld.txt:

Hello World!

[1]:

[To see links please register here]

[2]:

[To see links please register here]


Update:
As in Linux node write in current directory , it seems in some others don't, so I add this comment just in case :
Using this `ROOT_APP_PATH = fs.realpathSync('.'); console.log(ROOT_APP_PATH);` to get where the file is written.
Reply

#8
> ### [`fs.createWriteStream(path[,options])`](

[To see links please register here]

)
>
> `options` may also include a `start` option to allow writing data at some position past the beginning of the file. Modifying a file rather than replacing it may require a `flags` mode of `r+` rather than the default mode `w`. The encoding can be any one of those accepted by [Buffer](

[To see links please register here]

).
>
> If `autoClose` is set to true (default behavior) on `'error'` or `'finish'` the file descriptor will be closed automatically. If `autoClose` is false, then the file descriptor won't be closed, even if there's an error. It is the application's responsibility to close it and make sure there's no file descriptor leak.
>
> Like [ReadStream](

[To see links please register here]

), if `fd` is specified, [WriteStream](

[To see links please register here]

) will ignore the `path` argument and will use the specified file descriptor. This means that no `'open'` event will be emitted. `fd` should be blocking; non-blocking `fd`s should be passed to [net.Socket](

[To see links please register here]

).
>
> If `options` is a string, then it specifies the encoding.

After, reading this long article. You should understand how it works.
So, here's an example of `createWriteStream()`.

/* The fs.createWriteStream() returns an (WritableStream {aka} internal.Writeable) and we want the encoding as 'utf'-8 */
/* The WriteableStream has the method write() */
fs.createWriteStream('out.txt', 'utf-8')
.write('hello world');
Reply

#9
OK, it's quite simple as Node has built-in functionality for this, it's called `fs` which stands for **File System** and basically, **NodeJS File System module**...

So first require it in your **server.js** file like this:

var fs = require('fs');

`fs` has few methods to do write to file, but my preferred way is using `appendFile`, this will append the stuff to the file and if the file doesn't exist, will create one, the code could be like below:


fs.appendFile('myFile.txt', 'Hi Ali!', function (err) {
if (err) throw err;
console.log('Thanks, It\'s saved to the file!');
});

Reply

#10
The answers provided are dated and a newer way to do this is:

const fsPromises = require('fs').promises
await fsPromises.writeFile('/path/to/file.txt', 'data to write')

[see documents here for more info](

[To see links please register here]

)
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

©0Day  2016 - 2023 | All Rights Reserved.  Made with    for the community. Connected through