File System Module:
The Node.js file system module allows you to work with the file system on your computer. It exports functions for working with files and directories. The fs module is responsible for all the asynchronous or synchronous file I/O operations.
To include the File System module, use the require() method:
we can perform read, write, delete and many more operations. Let us look at some of the most important operations.
Reading Files Synchronously and Asynchronously
The fs module provides simple methods to read files: fs.readFile() and fs.readFileSync(). The fs.readFile() is for reading file asynchronously and fs.readFileSync() is for reading files synchronously.
Here, file path has to be provided as a first argument and a callback function that will be called with file data.
For fs.readFileSync(), file path has to be provided as a first argument. utf8 is the default encoding, but we can specify any custom encoding that we need as the second parameter in both the methods.
Writing Files Synchronously and Asynchronously
Create a new file using the fs.writeFile() and fs.writeFileSync() method. The fs.writeFile() is for reading file asynchronously and fs.writeFileSync() is for reading files synchronously.
In the synchronous write operation
Deleting a File
To delete a file with the File System module, use the fs.unlink() method.
Renaming a File
A file can be renamed using fs.rename(). Here, it takes old file name, new file name and a callback function as arguments.
Streams in Node.js
What is stream?
Streams are the collection of data like array or strings but the difference is that the all streams might not be available at a once and they don’t have to fit in memory. Stream is very useful to work with large amount of data and the data’s that’s come from the external source. They also give us power of composability in code.
Streams are also objects that we read data from a source or write data to a destination in continuous fashion.
Why Stream?
The advantage of stream is given bellow-
- Memory efficiency: No need to carry the massive amounts of data in memory before process it.
- Time efficiency: It takes way less time to start processing the data as soon as you have it, rather than waiting till the whole data payload is available to start the process.
Types of streams:
There are four types of streams. They are-
- Writable streams
- Readable streams
- Duplex
- Transform
We are going to describe about writable stream and readable stream.
Writable streams: Writable streams are the streams which data can be written. Writable object has a write() method which pass string or buffer to write something to the stream. And also a end() method that close the stream and give value in time of closing.
We can create a writable stream using createWriteStream() method. The example is given bellow-
Readable Stream: Readable stream is read data from source. The source can be simple file in file system, a buffer in memory, or even another stream.
creteReadStream() method is used to create a file readable from fs. Example is given bellow-
We can also read file using readFile() method.
Difference between writable Stream and Readable stream-
Screenshot captured from my Pluralsight course — Advanced Node.js
We know web technology works on the server site and client site. We will not go deep through this fact but we will just see how this simply works with http module in node.js.
In this article, we will know What is HTTP Module?, How can HTTP module be used to create server?. Then let’s start—-
Http Module:
Node.js has a built-in module called HTTP, which allows Node.js to transfer data over the Hyper Text Transfer Protocol (HTTP).
To include the HTTP module, use the require() method:
How can we use node.js as a web server using Http Module:
We can use createServer() method to create the server.
In above code, we imported {createServer} module using require directive to access HTTP module. The function passed into the http.createServer() method, will be executed when someone tries to access the computer on port 8000. The request and response bindings are objects representing the incoming and outgoing data. The first contains information about the request, such as its url property which tells us to what URL the request was made.
So, when one open that page in the browser, it sends a request to his/her own computer. This the causes the created server (In this case, server) to run and send back a response, which can be seen in the browser.
To send something back, response object works. writeHead() method set the server response type. Here, the content will be shown as html page. Multiple header may be use. The actual response method is sent with write() method. The call to server.listen() causes the server to start waiting for connections on port 8000. Finally, the response ends with response.end() method. If we initiate our code as –
We will see this in the browser as expected.
That’s for today. Happy Coding!!!!!
Reference-https://eloquentjavascript.net/20_node.html
This blog is a pixel art editor implements. please read the previous blog.
link: 1. http://enlightsolution.com/javascript/a-pixel-art-editor-how-to-create-a-canvas-draw-on-it/
2. http://enlightsolution.com/javascript/drawing-tools-in-a-pixel-art-editor/
When we’ve drawn our masterpiece, we’ll want to save it for later. So that we use this picture. We should add a button for downloading the current picture as an image file.
How to work save button?
The first step create the save button by elt() function. The elt() function get type, properties and child than finally return the DOM structure. Details elt() function please visit a previous blog, link: http://enlightsolution.com/javascript/a-pixel-art-editor-how-to-create-a-canvas-draw-on-it/
save() function call when the click save button. The component keeps track of the current picture so that it can access it when saving. The current picture get by state.picture. To create the image file, it uses a <canvas> element that it draws the picture on (at a scale of one pixel per pixel) by drawPicture() function. If you details, how to work drawPicture() function, visit previous blog, link: http://enlightsolution.com/javascript/a-pixel-art-editor-how-to-create-a-canvas-draw-on-it/
Again elt() function create another(<a>) tag. Here another tag attributes is href and download. The toDataURL method on a canvas element creates a URL. They are usually very long, but they allow us to create working links to arbitrary pictures, right here in the browser.
To actually get the browser to download the picture, we then create a link element that points at this URL and has a download attribute. The download attribute specifies that the target will be downloaded when a user clicks on the hyperlink(href). Such links, when clicked, make the browser show a file save dialog. We add that link to the document by document.boby.appendchild(), simulate a click on it, and remove it again.
How to work load-Button?
We’ll also want to be able to load existing image files into our application and edit this image. To do that, we again define a button component.
The load button create by elt() function, similarly to save button.
startLoad() function call when the click load button. To get access to a file on the user’s computer, we need the user to select the file through a file input field. But I don’t want the load button to look like a file input field, so we create the file input when the button is clicked and then pretend that this file input itself was clicked.
Finishload() call when input field change, here change means this input remove.
If a user no file selected, no execute other code. When the user has selected a file, we can use FileReader to get access to its contents, again as a data URL. That URL can be used to create an <img> element by elt() function, but because we can’t get direct access to the pixels in such an image, we can’t create a Picture object from that. The image path get by reader.result.
We already get the image. We’ll limit the size of images to 100 by 100 pixels since anything bigger will look huge on our display and might slow down the interface. Canvas tag again create by elt() function. The canvas element has a DOM method called getContext, used to obtain the rendering context and its drawing functions. This function takes one parameter, the type of context 2d.So getcontext method returns a drawing context on the canvas.
we use for drawing an image onto a canvas is the drawImage() function. context.drawImage(img,x,y), here img means specifies the image, x coordinate where to place the image on the canvas and y coordinate where to place the image on the canvas. Finally, draw in canvas. But, we do not have any color information. For that finish the work.
The data property of the object returned by getImageData is an array of color components. For every pixel in a getmageData object there are four pieces of information, which represent the red, green, blue, and alpha components of the pixel’s color. We need red, green, blue values, but not need alpha value. So we use the slice() function.
The hex() function return the hexadecimal digits. We have to make sure that each number takes up two digits, so the hex helper function calls padStart to add a leading zero when necessary. Finally, return the picture object.
‘A pixel art editor’ application will be a pixel drawing program, where one can modify a picture pixel by pixel by manipulating a zoomed-in view of it, shown as a grid of colored squares. One can use the program to open image files, drawing on them with mouse or other pointer device, and save them. An undo operation may be helpful also. That’s how it looks like-
This application has two portion. One is the canvas plot to draw the picture and the other is the different function panel below the canvas. But in this article, we will discuss about only how to create the canvas and draw on it with mouse.
THE STATE
We will go through state by state. The state contains the information of particular scenery of the application.
The application state will be an object with picture, tool, and color properties. The picture is itself an object that stores the width, height, and pixel content of the picture.
The pixels are stored in an array, in the same way as matrix row by row, from top to bottom. The draw method that expects an array of updated pixels—objects with x, y, and color properties—and creates a new picture with those pixels overwritten. This method uses slice without arguments to copy the entire pixel array—the start of the slice defaults to 0, and the end defaults to the array’s length.
Dom Building
We have the state and picture. Now we need to create our canvas. But we have to append the canvas in the document body using dom property. For knowledge about dom https://www.w3schools.com/js/js_htmldom.asp
The elt helper function provides a way to create an element and assigns property to domnode(not attributes) and child. This means we can’t use it to set arbitrary attributes, but we can use it to set properties whose value isn’t a string, such as ‘onclick’, which can be set to a function to register a click event handler.
Now, our dom building function is ready. We can start work for the canvas now.
THE Canvas
We said that, the first portion of the application is Canvas that displays the picture as a color of grid. It is responsible for two things: showing a picture & communicating mouse pointer event on picture. It doesn’t know how the application as a whole works. Rather, when responding to pointer events, it calls a callback function provided by the code that created it, which will handle the application-specific parts.If you need any knowledge about Canvas you can go through this https://www.w3schools.com/html/html5_canvas.asp.
We will draw the each pixel as 10 by 10 measurement as scale =10. The syncState method keeps track of its current picture and does a redraw only when syncState is given a new picture. Now let’s define the drawPicture mehod.
The drawing function sets the size(hight,width) of the canvas based on the scale and picture size and fills it with a series of squares, one for each pixel.
Now, what will happen when mouse pointer works on canavas? Lets do some stuff for that. When the left mouse button is pressed while the mouse is over the picture canvas, the component calls the pointerDown callback, giving it the position of the pixel that was clicked—in picture coordinates. This will be used to implement mouse interaction with the picture. The callback may return another callback function to be notified when the pointer is moved to a different pixel while the button is held down.
The PictureCanvas has additional method called mouse in it’s prototype. If you need to know what prototype is then you may read this article http://enlightsolution.com/uncategorized/prototypes-in-javascript/. Let’s define the pointerPosition method.
We can use getBoundingClientRect to find the position of the canvas on the screen, it is possible to go from mouse event coordinates (clientX and clientY) to picture coordinates. These are always rounded down so that they refer to a specific pixel. So we are getting the mouse position.
We said that we will not do all the functions here in the application. Our goal is to achieve this—
So, baseControls should be updated to baseControls=[ToolSelect,ColorSelect].
Now we’ll implement the main component (PixelEditor class) as a shell around a picture canvas and a dynamic set of tools and controls(Here just ToolSelect,ColorSelect) that we pass to its constructor.
The Control classes are—
Now we have to defind the draw tool that dispatches an action that updates the picture to a version in which the pointed-at pixel is given the currently selected color.
The draw function immediately calls the drawPixel function but then also returns it so that it is called again for newly touched pixels when the user drags or swipes over the picture.
The updateState function can compute a new state. We’ll allow the interface to dispatch actions as objects whose properties overwrite the properties of the previous state.
Now we can test our application—
And here is our desire output—
Thats how the Canvas and drawing a picture works in Pixel Editor tool.
Happy Coding :)!!!!!!!!
Undo Action in Pixel art editor
In pixel art editor undo action is work for remove element which we art in the editor. Always it remove the recent element from the editor and update the image.
Why we need it?
Sometimes we may have some mistakes when we art in the editor. Also some unnecessary things may be drawn. So we have to remove those unnecessary things. That’s why undo action is needed. Undo action is an important feature in this editor.
In picture1 and picture2 the mistakes or unnecessary elements are marked in a circle. We will use undo action to remove those.
How Undo works?
When we press the undo button the latest update is removed from the image. To find the latest update we need to save every update of the image. So we use an done array to save every update state. And to insert the image into the array we use a method historyupdatestate().
To remove the image this editor has an undo button to maintain it.
Firstly we the undo button to start undo action and then to update the picture a update State method is needed.
Undo button:
Undo button does not do everything. It just dispatch undo action when we click in undo button and disable itself when there is nothing to undo.
Here Undo action will be true on click the undo button.
State.done is an array of pictures which we draw in the editor. “State.done.lenght==0” define that there is no image in the array that means no picture is drawn in the editor so nothing to undo. So undo button will be disabled.
Here we can see that undo button is disable when nothing is drawn and enable after drawing.
Image Update:
To update image based on action a historyUpdateState() method is used. When the action is undo then it check in done array for image. If it is empty then no update works otherwise the latest image will be removed from the array.
When we draw anything in editor the image will be saved in first position of done array.
If the action is contain a new picture and last picture is saved more than 1000 milliseconds ago. It takes the new picture as done[0] (first element of the done array) and the previous elements(pictures) are kept from done[1]. And object.assign() update the state.
In historyUpdateState() functions when action is undo it takes the most recent picture as current picture and make doneAt to zero. And state.done.slice(1) extract the pictures from done array. It update the array elements by deleting done[0] element which contains the latest picture. Here Object.assign() is used to update the property of the state.
here the latest image has deleted after click undo button from done array.
After update the state it show the picture which is on the current state that is state.done[0].