Files and Streams-Node.js essential knowledge 4

Haifeng Wang
2 min readOct 15, 2020

The stream interface provides us with the technique to read and write data. We can use it to read and write data to files, to communicate with the internet, to communicate with other processes.

Readable File Stream

const readStream = fs.createReadStream("./folder/filename", "UTF-8");let fileText = "";console.log("Type something ...");readStream.on("data", data => {
console.log(`I read ${data.length - 1} characters of text`);
fileText += data;
})
readStream.once("data", data => {
console.log(data);
})
readStream.on("end", () => {
console.log("finished reading file");
console.log(`in total I read ${fileText.length-1}`);
})
process.stdin.on("data", data => {
console.log(`I read ${data.length - 1} characters of text`);
})

Writable File Stream

const writeStream = fs.createWriteStream("./folder/filename", "UTF-8");process.stdin.on("data", data => {
writeStream.write(data);
})
# we can also use readStream to write file
const readStream = fs.createReadStream("./folder/filename", "UTF-8");
readStream.on("data", data => {
writeStream.write(data);
})
# We use pipe function to acheive the same result
process.stdin.pipe(writeStream);
readStream.pipe(writeStream);

Create Child process

Node.js comes with a child process module, which allows us to execute external processes in the environment, in other words, nodejs app can run and communicate with other applications within the environment that is hosted. There 2 main functions used to create a child process, spawn and execute.

The execute function is for syncronous commands.

const cp = require("child_process");
cp.exec("open URL");
cp.exec("ls", (err, data) => {
if(err){
throw(err)
}
console.log(data);
})
cp.exec("ls", (err, data, stderr) => {
if(err){
throw(err)
}
console.log(stderr);
})

The spawn function when we want to wait a event happen

const cp = require("child_process")const nameaApp = cp.spawn("node", ["nameaApp.js"]);# we can send spawn process using standard input
nameaApp.stdin.write("message1 \n");
nameaApp.stdin.write("message2 \n");
nameaApp.stdout.on("data", data => {
console.log(`From this app: ${data}`);
})
nameaApp.on("close", () => {
console.log("this app process exited");
})

--

--