0

I am trying to figure out how to import an image from my desktop into a .js file.

var express=require("express");

var http=require("http");

var app=express();
var img = new Image();
var div = document.getElementById('foo');

img.onload = function() {
    div.appendChild(img);
};

img.src = C:\Users\image location

http.createServer(app).listen(11111);

console.log('Express server listening on port 11111');
4
  • Please fix syntax errors & formatting. Then make sure you understand the difference between a client (document.getElementByID) and a server (read on) Commented Dec 29, 2018 at 12:25
  • Looks like you're mixing up client side and server side code. Express only works on the server side, while document.getElementById only works on the client side (browser) Commented Dec 29, 2018 at 12:35
  • See the link expressjs.com/en/starter/static-files.html Commented Dec 29, 2018 at 12:44
  • You refer to this article as well dzone.com/articles/… Commented Dec 29, 2018 at 12:48

2 Answers 2

0

Use node's built-in file system module.

var fs = require('fs');

Example given on W3schools.com:

fs.readFile('picture.jpg', function(err, data) {
    ...
    ...
});

As far as your code, DOM-manipulating js should not be in server-side code. For instance:

var div = document.getElementById('foo');

This should be moved to a client-side file.

See this Stack Overflow answer about importing images.

Sign up to request clarification or add additional context in comments.

Comments

0

Well, first of all this code is server side so you cannot use the function document.getElementById. Now if you want to send an image to a client when they request to a specific endpoint, that can be done fairly easily.

import fs from 'fs';
import express from 'express';
const app = express();
app.get('/sendImage', (req, res) => {
    const readStream = fs.createReadStream('path/to/image.jpeg');
    readStream.pipe(res);
});

On the client side you can show image like this

<img src='localhost:11111/sendImage' />

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.