Node JS provides synchronous and asynchronous methods for reads and writes local files. When you use the synchronous method, the execution thread will be blocked until the process complete, and you need to catch the exception by yourself in code.
When you use the asynchronous method, you need to provide a callback function as the second parameter, and the callback function’s first parameter is an error object to represent the errors during file operation.
In the asynchronous method, the read/write file event will be put into the event loop, so the node js code process will not be blocked. Only when the file operation complete, the callback method will be invoked by the event loop.
1. Node JS File Operation Preparation.
No matter which method you want to use, you must first import the node js fs module into your code as below.
var fs = require('fs');
Because this article example will use a third-party module thread-sleep to make the main thread sleep for some time, so you need to install the module into your environment by npm as below.
Open a terminal and run the below command. Of course, you need to switch to root user using # su
command if you are not.
# npm search sleep # npm install thread-sleep -g
After running the above commands, you can find the thread-sleep module in the /usr/local/bin/node_modules
folder.
2. Open And Close File With Node.js.
2.1 Synchronous Open File.
fs.openSync(filePath, 'r+')
: Open file synchronously.
fs.closeSync(fd)
: Close file synchronously.
// This third party module is used to make current thread sleep for some milliseconds. var sleep = require('thread-sleep'); // Import node js fs module. var fs = require('fs'); function openFileSync(filePath) { try { var startDate = new Date(); /* Open a file for read and write. The second parameter can be r(reading), w(writing), a(appending), r+(w+)(read and write), a+(reading and appending)*/ var fd = fs.openSync(filePath, 'r+'); // Sleep one second. sleep(1000); // Close the file. fs.closeSync(fd); var stopDate = new Date(); var deltaTime = stopDate - startDate; console.log("delta time = " + deltaTime); }catch(error) { // If the file do not exist, then this error will thrown. console.error(error); } } openFileSync('test.txt');
Below is the output of the above code.
/usr/local/bin/node /Users/zhaosong/Documents/WorkSpace/dev2qa.com-example-code/JavaScriptExampleWorkspace/NodeJSWorkspace/FileReadWrite/read_write_file.js delta time = 1011 Process finished with exit code 0
2.2 Asynchronous Open File.
fs.open(filePath, 'r', callback_function(err, fd))
: Open file asynchronously.
fs.close(fd)
: Close the file asynchronously.
// This third party module is used to make current thread sleep for some milliseconds. var sleep = require('thread-sleep'); // Import node js fs module. var fs = require('fs'); function openFileAsync(filePath) { var startDate = new Date(); /* The first parameter is filePath, the second parameter is r(read), w(write), r+(w+)(read and write), * The third parameter is a callback function which will be executed after file operation. */ fs.open(filePath, 'r', function (error, fd) { sleep(1000); if(error) { console.error(error); }else { fs.close(fd); console.log('file is closed.') } }) var stopDate = new Date(); var deltaTime = stopDate - startDate; console.log("delta time = " + deltaTime); } openFileAsync('abc.txt');
Below is the output of the above Node.js code execution.
/usr/local/bin/node /Users/zhaosong/Documents/WorkSpace/dev2qa.com-example-code/JavaScriptExampleWorkspace/NodeJSWorkspace/FileReadWrite/read_write_file.js delta time = 1 { Error: ENOENT: no such file or directory, open 'abc.txt' errno: -2, code: 'ENOENT', syscall: 'open', path: 'abc.txt' } Process finished with exit code 0
3. Read File.
3.1 Simple File Reading.
These methods will read the file content as a whole buffer data and return it.
3.1.1 Synchronous SimpleFile Read.
We can use the fs.readFileSync(filePath, options)
method to read the file synchronously.
function simpleReadFileSync(filePath) { var options = {encoding:'utf-8', flag:'r'}; var buffer = fs.readFileSync(filePath, options); console.log("File content : " + buffer); } simpleReadFileSync('test.txt');
Output
File content : this is a test text file.
3.1.2 Asynchronous Simple File Read.
We should use the fs.readFile(filePath, options, function (err, data) { })
method to read the file content asynchronously.
function simpleReadFileAsync(filePath) { var options = {encoding: 'utf-8', flag: 'r'}; fs.readFile(filePath, options, function (err, data) { if(err) { console.error(err); }else { console.log("File content : " + data); } }); } simpleReadFileAsync('test.txt');
3.2 Synchronously File Reading.
These methods can read file data into a buffer object with a specified byte count.
function readFileSync(filePath) { var fd = fs.openSync(filePath, 'r'); var content = ''; var buffer = new Buffer(10); buffer.fill(0); var readCount = fs.readSync(fd, buffer, null, 10); while(readCount > 0) { console.log("Read " + readCount + " bytes."); content += buffer.toString().substr(0, readCount); readCount = fs.readSync(fd, buffer, null, 10); } fs.closeSync(fd); console.log("File content : " + content); } readFileSync('test.txt');
Output
Read 10 bytes. Read 10 bytes. Read 5 bytes. File content : this is a test text file.
3.3 Asynchronously File Reading.
var fileContent = ''; function readFileAsync(fd) { var buffer = new Buffer(10); buffer.fill(0); fs.read(fd, buffer, 0, 10, null, function (err, readCount, data) { console.log("Read %d bytes.", readCount); if(readCount > 0) { fileContent += data.toString().substr(0, readCount); readFileAsync(fd); }else { fs.close(fd); console.log("File content : " + fileContent); } }) } fd = fs.open('test.txt', 'r', function (err, fd) { if(!err) { readFileAsync(fd); }else { console.error(err); } });
3.4 Stream File Reading.
function readFileStream(filePath) { var fileReadStream = fs.createReadStream(filePath, {encoding:'utf8', flag:'r'}); fileReadStream.on('data', function (data) { console.log("Read data length : " + data.length); console.log("Read data : " + data); }); fileReadStream.on('close', function () { console.log("File is closed. "); }); } readFileStream('test.txt');
Output :
Read data length : 25 Read data : this is a test text file. File is closed.
4. Write File.
4.1 Simple File Writing.
Write whole file content at one time.
4.1.1 Simple File Synchronous Writing.
function simpleFileWriteSync(filePath, content) { var options = {encoding:'utf-8', flag:'w'}; fs.writeFileSync(filePath, content, options); console.log('Write file data complete.') } simpleFileWriteSync('abc.txt','hello welcome to node js.')
4.1.2 Simple File Asynchronous Writing.
function simpleFileWriteAsync(filePath, content) { var options = {encoding:'utf-8', flag:'w'}; fs.writeFile(filePath, content, options, function (err) { if(err) { console.error(err); }else { console.log('File content saved. '); } }); console.log('Write file data complete.') } simpleFileWriteAsync('abc.txt','node js file operation is not difficult.')
4.2 Synchronous File Writing.
Write data to file with buffered content, not whole content at once.
function fileWriteSync(filePath) { var fd = fs.openSync(filePath, 'w'); var codingArray = ['Java', 'JavaScript', 'C++', 'C', 'C#', 'Node JS']; var length = codingArray.length; for(var i=0;i<length; i++) { var bytes = fs.writeSync(fd, codingArray[i] + '\n', null, null); console.log('Write string %s which is %d bytes.', codingArray[i], bytes); } fs.closeSync(fd); } fileWriteSync('coding.txt');
Output :
Write string Java which is 5 bytes. Write string JavaScript which is 11 bytes. Write string C++ which is 4 bytes. Write string C which is 2 bytes. Write string C# which is 3 bytes. Write string Node JS which is 8 bytes.
4.3 Asynchronous File Writing.
function fileWriteAsync(fd) { var codingArray = ['Java', 'JavaScript', 'C++', 'C', 'C#', 'Node JS']; var length = codingArray.length; for(var i=0;i<length; i++) { fs.write(fd, codingArray[i] + '\n', null, null, function (err, bytes, data) { console.log('Write string %s which is %d bytes.', data, bytes); }); } fs.close(fd); } fs.open('language.txt', 'w', function (err, fd) { if(!err) { fileWriteAsync(fd); }else { console.error(err); } })
4.4 Stream File Writing.
function writeFileStream(filePath, data) { var writeStream = fs.createWriteStream(filePath, {encoding:'utf-8', flag:'w'}) writeStream.write(data); writeStream.on('close', function () { console.log('Write stream is closed. '); }) } writeFileStream('stream_writing.txt', 'Hello this is node js stream writing example.');
Wish everybody a happy new year:)
Happy spring festival : )
The same to you, thanks.
readFileSync Why does this only return the first character of the string?
“`
const searchkeywords = fs.readFileSync(‘kwords.csv’,’utf-8′);
for (let kword of searchkeywords) {
console.log(`Search Keyword: ${kword}`);
“`
Text for the first 10 rows is:
“1-800-FLOWERS.COM, INC.”,
“1ST SOURCE”,
“1ST SOURCE CORP”,
“3D SYSTEMS”,
“8X8, INC.”,
“A.H. BELO”,
“AAON”,
“AARON RENTS”,
“ABERCROMBIE & FITCH”,
“ABIOMED”,
You can use other method such as method in section ( 3.2 Synchronously File Reading ) to read your file content, or you can read your file content asynchronously. And you should debug your code if you like.
thank you for your reply, it is very helpful.